Master UseState Hook by Building Simple Apps with React

Master UseState Hook by Building Simple Apps with React

Hello there! Trust you're doing great. In this post, I'll be taking you through how you can smartly work with React Hook's useState, to manage your app's state efficiently like you're a PRO. If you aren't yet, trust me you'll be by the end of this article.

Getting Started

These days, most of the developers I know build their app components using functional components. In some old versions of React, class was the only way to work with states, until 2018 when React Hooks introduced at React Conf in October 2018 as a way to use state and side-effects (see lifecycle methods in class components) in React function components. Meanwhile, it was stated by the React team that the popular class-based component approach won't be deprecated anytime soon.

Haven said this, developers are free to use whatever approach they are comfortable with. In my case, I prefer working with function-based components, which gives me the flexibility of handling my app's state right from a function. Cool Isn't it?

Apps you will be building

  • AudioControl: An app with four buttons to control the volume, bass, treble, and Mid of a speaker.
  • LightBulb: An to simulate switching of bulbs.
  • Random List Generator: An app to generate a random list of numbers.
  • Multi-Counter: An app list multiple counters.
  • Step Tracker: An app to track the step we've taken as a particular button is clicked.

Let's dive in

Taking it from the root, what is a state? state in simple a term means data store. A state is a part of our application where the data needed are stored. Say we are building a note-taking app, we'll need a place to store our state. Sure! Depending on the structure of the data, we can determine which kind of data type to store the data with Array, Integer, Boolean, and Boolean. In this case, we will be using an array as follows:

const notes = [
   {
     id: 1,
     title: "React Hooks",
     body: "All you need to know about react hooks"
   },
  {
     id: 2,
     title: "React useState Hooks",
     body: "All you need to know about useState Hooks"
    }
]

In class-based components, we can represent our app state with:

  this.state = {
        notes = [
            {
               id: 1,
               title: "React Hooks",
               body: "All you need to know about react hooks"
            },
           {
             id: 2,
             title: "React useState Hooks",
             body: "All you need to know about useState Hooks"
          }
      ]
  };

There is a central state object in every class-based component which holds the data required by the application. And you are provided with a setState() function which allows you to update the part of your state you which to update.

Enter React useState Hooks

Without much delay, useState is a Hook that lets you add React state to function components. And how on earth does it do that. Like every other hook in react, useState starts with the prefix "use". Let me show you how it works with an example.

const [count, setCount] = useState(0)

count above is the state variable, with an initial value of 0, while setCount is the function which will update the count variable.

While the example above is a very good way to illustrate how useState works, a state can much more complex than that. Just like every other variable, a state variable can assume any value ranging from integer, array, and object. Don't fret!! Several examples will be used to help you better understand the use of state in any form.

Let get our hands dirty

The first app we'll build is a Step Tracker. How the app works is: the step taken by the user will increase or decrease by the number of times the buttons are clicked. To make work faster, I prefer building apps in Code Sandbox. Here is the code. The goal of this app is to work with integer state values.

const StepTracker = () => {
  const [steps, setSteps] = useState(0);

  // function increment() {
  //   setSteps((steps) => steps + 1);
  // }
  return (
    <div>
      <h2>I will update the state from the previous state</h2>
      <h3>You have taken {steps} steps!</h3>
      <br />
      <button onClick={() => setSteps((steps) => steps + 1)}>
        I took another step
      </button>
    </div>
  );
};

export default StepTracker;

From the code above, we declare a state variable steps and initialize it with value 0. We then update the state variable using the setCounter value. We achieve that using the following code.

setSteps((steps) => steps + 1)

Common mistakes people do is to update the state this way: setSteps(count + 1);

It would work but to be sure that we are working with the latest state, we use this approach. setSteps receives steps as an argument and returns its updated version. In this case, it's incremented version.

And an onClick was added and the onClick is assigned with the update function.

You can place the StepTracker component in App component to test it out.

Conclusion

In the next article, we will be learning how to manage a state from an array.