React Hook : useState()

How state work under the hood

·

2 min read

The useState() function

useState() function takes in a changeable value and returns an array of exactly 2 elements. Where the 1st element is the updated value itself, and the 2nd element is the updating function.

const [title,setTitle] = useState('');  //initialize to empty string

Why use useState() function instead if a normal assignment?

//this does not work as it will not 
//re-render the UI to show the updated value
title = "something"

In order for React to re-evaluate the function again, or rather to re-render the new updated value at frontend, we have to use useState() function.

React managed it by storing this useState() function somewhere in the memory, and when setTitle() is called, it will re-execute the whole instance of the component function where useState() is called.

Why using const when we do eventually assign a new value?

const [title,setTitle] = useState('');

When we change a value, we are calling setTitle(), we never do any assignment to the title variable itself. So having declared a const is totally fine. In order for the title value to be updated, React helps to re-evaluate the component instance when setTitle() function is called, and thus grabbed the new title value.

const App = () =>
{
  //1. We define useState() function here, React will store it in memory
  //5. React will re-run this App() component once where useState() is declared
  const [title, setTitle] = React.useState('Hello World!');

  //2. Declare a titleHandler for button to trigger
  //4. When onClick handler is triggered, setTitle() is called to update new value to title
  const titleHandler =()=>{
    setTitle('Updated to New Word!');
  }

  //3. Assign the title variable at the frontend
  //6. The UI will be re-rendered, displaying the updated title at frontend
  return (
    <div>
      <h1>Title is: {title} </h1>
      <button onClick={titleHandler}>Update title</button>
    </div>
  );
}

Try it out in codepen here! codepen.io/yipcode/pen/eYeVEJo?editors=1111