UseState Hook Demystified

What is useState? Why do I even need it? Why is my UI not updating when I use const? Slow down, newbie😅. We were all here before, but in this article, I'm going to show you how to use the useState hook like a pro.


You might be wondering, "Why do I need it?" Alright techie, here is a use case. Imagine we're building a counter app that updates on every button click. The code snippet below updates the text in the p tag when the button is clicked.

function App() {
  let count = 0;
  console.log(count);
  return (
    <>
      <p>You clicked this button {count} times!</p>
      <button
        onClick={() => {
          console.log(count);
          count = count + 1;
        }}
      >
        Count
      </button>
    </>
  );
}
export default App;

We have this result:

illustration of using const to update state

Oh no🥺! The counter value is being logged to the console but not updated in the UI! What do we do?

Alrighty, I did that on purpose. Using const or let to reassign or in this case update variables only works in memory, it doesn't affect the UI and in such cases, might make the UI and state fall out of sync.

So, we need a solution that anytime our variable changes, it makes sure the UI is updated along. I know you already know the answer, yeahhhh! we're making use of the useState() hook.

The useState() hook is the easiest React hook to use. It can be initialized like this:

  • First, we import the useState() hook from React

import { useState } from 'react

  • Now we initialize it in our app

const [counter, setCounter] = useState(0)

Looks confusing? I'll explain. We call the useState hook and it returns an array which we destructure immediately.

First variable is the state value itself and the second is the state updating function, which we call anytime we want to update or change the value of the state.

Did you notice that we pass the initial value of count 0 when we call useState()? Alright! you're following up. It simply tells React that we first want this state's value to be 0.

Notice the naming convention, the first value represents the name of the state and the other uses the prefix set then the state's name. This is a common convention among React Developers and it's advisable to follow suit.

Let's try making our counter this time in the React way using the useState() hook.

import { useState } from "react";

function App() {
  const [counter, setCounter] = useState(0);
  console.log("counter");
  return (
    <>
      <p>You clicked this button {counter} times!</p>
      <button
        onClick={() => {
          setCounter(counter + 1);
        }}
      >
        Count
      </button>
    </>
  );
}
export default App;

From the code snippet, we initialize the useState() hook and give it the initial value of 0, so the counter variable is 0 at first. Then when the button is clicked, we update the counter variable by using the state updating function the useState() hook returns. We add one to the previous value of the counter.

counter app with the usestate hook

From the above image, we can see that the state and the UI are being updated. Why? Anytime a state changes in React, the particular component triggering the state is re-rendered.

Consider the above image, anytime the button is clicked, it's logging something to the console. That's because, anytime we click the button, the state is updated (we add one to the state) and because of that change, the component is re-rendered and the console.log() is executed again. When React re-renders the component, it makes sure that the state and UI are in sync.

So now we know we use the useState hook anytime we need to keep track of state changes in React.

Note: We use state mainly when we need changes that also needs to be updated in UI.

I hope I demystified the useState() hook for you. Like, Follow and Comment for more articles where i demystify React hooks

No comments:

Post a Comment