DEV Community

Cover image for useState hook simplified!
Aman Kumar Singh
Aman Kumar Singh

Posted on

useState hook simplified!

Lets Begin the discussion

useState is a react hook, we call it inside a functional component to add some local state to it. Between re-renders React actually preserves the state.

useState returns a pair

  • 1. current state
  • 2. function that lets you update it.

this is how you declare const [ age, setAge ] = React.useState(10);

consider this functional component, it updates the age.

const Age = () => {
     const [ age, setAge ] = React.useState(10);
     // Onclick function to update the state
     const updateAge = ()=> {
           setAge(age => age + 1);
     }
     return (
             <div>
                <button onClick={updateAge}> {age}</button>
             </div>   
    );
}
Enter fullscreen mode Exit fullscreen mode

What happens here lets discuss

  • Whenever this button is clicked updateAge function is called.
  • The setAge method is called and state is updated.
  • The Component renders.
  • useState is called for updated state value.

This perception is very Wrong !!, personally, I had the same misconception. To clear this and prove this point, I will ask you a question

Did it ever occur to you that useState hook doesn't update immediately ?

The answer to this is because they don't make any direct change to the state object, instead they create queue to optimize performance. This is why they Do not reflect immediately.

React.useState create queues for React core to update the state object of a React component.

So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.

Since react.useState is asynchronous now how someone will perform something after after react state is changed

 const Age = () => {
     const [ age, setAge ] = React.useState(10);
     // Onclick function to update the state
     const updateAge = ()=> {
           setAge(age => age + 1);
     }
     // This part will act as a callback whenever state updated 
     React.useEffect(()=>{
     if(age < 0){
        alert("Age can't be less then 0, you dumb");
      }
     },[age])
     return (
             <div>
                <button onClick={updateAge}> {age}</button>
             </div>   
    );
}
Enter fullscreen mode Exit fullscreen mode

Rules for using useState

  • 1. Only call Hooks at the top level.
  • 2. Only call Hooks from React functions

Thanks for Bearing,
I will be writing articles explaining each hook provided by react in upcoming articles please follow to stay connected.

Top comments (3)

Collapse
 
aminnairi profile image
Amin

Do not forget to wrap your callbacks inside of your components with a useCallback.

import React, {useState, useCallback} from "react";

const Example = () => {
  const [counter, setCounter] = useState();
  const increaseCounter = useCallback(() => setCounter(oldCounter => oldCounter + 1), []);

  return (
    <button onClick={increaseCounter}>Increase ({counter})</button>
  );
};
Enter fullscreen mode Exit fullscreen mode

That way, your callback does not get recalculated each time your component is rendered (when the state is updated). This will prevent the client from unnecessarily redefining a function that does not change over time (since there are no dependencies).

Or, define the function outside of your component using an Inversion of Control.

import React, {useState} from "react";

const updateCounterWith = setter => () => setter(counter => counter + 1);

const Example = () => {
  const [counter, setCounter] = useState();

  return (
    <button onClick={updateCounterWith(setCounter)}>Increase ({counter})</button>
  );
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
amankumarsingh01 profile image
Aman Kumar Singh

Thanks fr sharing

Collapse
 
maske_sankett profile image
Sanket Maske

Thank you this really helped me