Let's Connect
aura menu

A beginner’s guide to React Hooks

Subham

TreeImage
TreeImage

Does it ever seem like React Hooks is mind-boggling?

Like I felt when I heard about them.

It was 3-4 months ago when I started using React Hooks and I am really fascinated. Till React 16.7 Class components comprised the whole world of React Library.

With Hooks the state management becomes so flexible and easy. In Class components, we had lifecycle methods and quite a lot of them. But, as far as I understood for Hooks you need two Hooks to compensate with most of the lifecycle methods.

1) useState

2) useEffect

There are many more, but these two form the basics of hooks. Don’t worry about the above hooks now, we will go into the details of useState in a bit.

Now one might ask, What is a Hook??

Here’s the React definition:

Hooks are functions that let you “hook into” React state and lifecycle features from function components. 

Hooks don’t work inside classes — they let you use React without classes.

It’s pretty straight forward but let me simplify it a bit more, Hooks are simple JavaScript functions that help you with State management of the Functional components.

And just like any other JS function, we call hooks in the same way “function_name(arguments)”.

UseState:

Here’s a simple example :- useState(0);

I think it’s not wrong to assume that you are familiar with this syntax,

const [state, setState] = useState(0);

What’s happening here?

In simpler terms, Destructuring the return value of the useState hook.

Two things to notice here, one is the argument to the hook and another is the return value.

-Argument to this hook can be any valid Javascript data type like a number, string, array, object.

-Now let’s move on to the return values, one is “state” and another is “setState”, their name can be any valid identifier.

“state” is the variable that stores the value and “setState” is an async function that helps us to change the value of “state”.

Some of the examples include :-

const [fruit, setFruit] = useState(‘banana’);

const [todos, setTodos] = useState([{ text: ‘Learn Hooks’ }]);

The question that might come to everyone’s mind is “How to use setState function?”

1) Call setState with the new value of state

2) Pass a callBack function that returns the new value of state

What happens when we call the setState function?

– One of the answers is “Obviously the value of state will change”, but no that’s not it.

Along with that the component also re-renders, and I am pretty sure you are familiar with the React Virtual DOM concept and how it updates the DOM.

Here’s a code snippet to illustrate both the ways of using setState :

Do make sure to try it out in any sandbox and play around with it a bit.

export const App = () => {

  const [state, setState] = useState(1);

  const reset = () => {

    setState(1); // First way, directly passing the new value

  };

  const customCalculate = () => {

    setState(

// Second way, passing a callback function that returns the final value.

value => {

      return 5 * value;

    }

);

  };

  return (

    <>

      <div>

        <div>State:-</div>

        <div>{state}</div>

      </div>

      <button onClick={customCalculate}>Multiply with 5</button>

      <button onClick={reset}>Reset</button>

    </>

  );

};

You might have noticed that the callback to the setState function has an argument named “value”, what is that? 

Well, that’s another feature of the useState hook, “value” stores the current value of the state i.e before changing.

useState, that’s it? Yes!! But hold on we got another one, it is useEffect.

Check Out this blog: Redux and it’s 4 components

UseEffect:

Before that, What’s an effect?? A piece of code that we want to run after React is done with DOM Rendering.

Why do we need it?? Network calls, subscriptions, and a lot more.

Here’s the syntax of useEffect

useEffect( () => {

// Side Effect

return function cleanup(){}

},[…statesArray])

Three important things in the syntax above 

1) Side Effect

2) cleanup function

3) statesArray

Let’s go through them one by one

Side Effect :

This is the effect, that runs after every render

Cleanup:

It’s an optional function, useEffect doesn’t have to return something. And it can be any JS function, no need to go with the name “cleanup”.

It clears up the effect on the unmounting of the component as well as before running the same useEffect next time.

statesArray:

It’s an optional argument to useEffect. What is it for? It’s something that controls when the useEffect will run.

If no array is provided, then it’s the default behavior, useEffect will apply after every render

If an empty array is provided,  then it will run only when the component mounts

What if you provide some values in the array?

useEffect will run only after the mentioned states in the statesArray are initialized or updated.

It contains the list of local states of the component.

Checkout the sandbox here: Codesandbox

Play around with it!!

What we discussed till now was the Syntax and the implementation of useState and useEffect hook, pretty simple JS, right!!

This was just the beginning of Hooks, there is plenty more to discuss the React Hooks!!!

Till then, Happy Hacking!!

You can find more how-to blogs related to React, Redux, Android, and much more HERE.

Read Also: What is React JS vs. Angular: A Complete Guide for 2023

butterfly
Let'sTalk
butterfly
Thanks for the submission.