DEV Community

Sana Mohiuddin
Sana Mohiuddin

Posted on

Hooks in React

React is a powerful tool for javascript users, it is a library that allows us programmers to create user interfaces much more efficiently than just using vanilla javascript. React gives us a way to create our programs declaratively. Declarative programming is determining what you want the end result to be without going step by step. Imperative programming is what you would do with plain old javascript going step by step describing how you would like to manipulate the DOM.

const button = document.createElement('button');
button.textContent = "Click Me";
const body = document.querySelector('body');
body.appendChild(button);
Enter fullscreen mode Exit fullscreen mode

In the above example, the programmer must step by step tell the computer what to do, from creating the button element to finding where it should go and lastly appending it the correct element. With React we can use JSX which is similar to do those same steps quicker.

return(
   <button>Click Me<button>
);
Enter fullscreen mode Exit fullscreen mode

The JSX shown above is then converted using Babel into something the computer can understand. This quick introduction to React is to get you ready for the real topic, and that is hooks. Hooks are special react functions that allow you to essentially "hook" into components' state and lifecycle. There are a multitude of different hooks in React , but the ones we will focus on are the useState and useEffect hook.

The useState Hook

Probably the most important hook that you can use is the useState hook. As was said earlier, hooks are special because they allow you to "hook" into different things. In this case, it will be hooking into the components state. State is a special React object that contains information about data regarding a component. Whenever that data is changed, the component will re-render based on the new data.

How To Use The useState Hook

In order to use the useState, it will need to be imported in the file that you will be using it in, just like you need to import React.

import React from "react";
Enter fullscreen mode Exit fullscreen mode

The above example shows how to import React, but we need to add another detail to be able to utilize the useState hook.

import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

With that line of code, we are all ready to begin. Consider the code snippet below:

import React from "react";

function MyButton() {
   function handleClick() {
      console.log("On");
   }

   return (
      <div>
         <h2>Click the Button</h2>
         <button onClick={handleClick}>Off</button>
      </div>
   );
}
Enter fullscreen mode Exit fullscreen mode

We have a component called MyButton that has a button that when you click it, it will print on the console "On". However, what if we want the button text to change between "On" and "Off" based on when the user clicks it. We can do that by implementing the useState hook.

import React, { useState } from "react";

function MyButton() {
   const [isOn, setIsOn] = useState(false);

   function handleClick() {
      setIsOn(!isOn);
   }

   return (
      <div>
         <h2>Click the Button</h2>
         <button onClick={handleClick}>
            {isOn ? "On" : "Off"}
         </button>
      </div>
   );
}
Enter fullscreen mode Exit fullscreen mode

Some of the code above may look new, the first line of the function is where you initialize state. It may look strange but we declare it with a de-structured array, because when you use the useState hook, it returns two things. First a variable that holds the current state, and second a setter function to change the value of the state. Always use the setter function, do not set it directly with the variable. One of the perks of the setter function, is when it is called and state is changed the component will re-render itself. In the example above the button has a text that changes based on state using conditional rendering. Whenever the button is clicked the text should fluctuate between "On" and "Off", without needing to refresh the page. This is just one of the ways to use the useState hook, it is a very helpful tool that makes your website more responsive and user friendly.

The useEffect Hook

The useEffect hook by default, runs a set of statements every time the component renders. Just like with the useState hook, you need to import it, in order to be able to use it.

import React, { useEffect } from "react";
Enter fullscreen mode Exit fullscreen mode

There are many different uses for the useEffect. One example could be to set a timer that restarts each time the component re-renders. Take a look below to see an example of the useEffect being used below.

useEffect(() => {
   console.log("Component has be rendered");
});
Enter fullscreen mode Exit fullscreen mode

This is just a quick example to show the syntax of the useEffect hook. Within the call of the hook is a function that will be run at every component render, as previously stated. However, sometimes you do not want the function to run at every render, but only once or sometimes. This can be accomplished with a dependency array that is put down as the second parameter of the useEffect hook function call.

useEffect(() => {
   console.log("Count has been changed");
}, [count]);
Enter fullscreen mode Exit fullscreen mode

When there is a variable within the dependency array, the function will run the first time the component renders, as well as each time the value of the variable changes. There can be multiple values in the array. There can also be no values in the dependency array, which would cause the function to run only the first time it is rendered. An important use of an empty dependency array is when you are fetching data from an API, you usually only need to that once initially.

Conclusion

Hooks are a valuable tool to use when programming in React. Hopefully, you have learned enough and can get to practicing, because remember practice makes perfect.

Resources

Discussion (0)