Managing State in React

We have not added interactivity to our components yet. In this article, we are going to give our application some memory so that we can create a simple todo application.

This article introduces state management in React and how it helps create interactive and dynamic user interfaces.

Managing State

What is "State"?

State in React can be considered a snapshot of an application at a point in time, holding data that influences the behavior and rendering of components.

Or, to simplify it a bit more, think of it as a way of giving memory to our components.

When this state is updated, our component rerenders and shows the new state if applicable.

To use state in React, we first import useState from React.

import { useState } from 'react';

useState accepts the initial value of the state and returns an array containing the value of the state and a way to set the state (something like [myValue, setMyValue], and we access the values like this:

function Counter() {
  const [count, setCount] = useState(0);

We must update the state using this setter function and reference it using the state so that React can track the changes in our application and show them.

As you can see, we destructure these values from useState. When I first came across this syntax, it confused me because I had never had to use array destructing practically.

For example, let's create a click counter that counts the number of times a user clicks a button.

import { useState } from 'react'

const Counter = () => {
  const [count, setCount] = useState(0)

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
    </div>
  )
}

Try it out in an interactive CodeSandbox try it out here:

Here's a simplified visualization of what's happening to create the update:

Simple diagram of Counter component rerendering

Or here is an example with several instances of our Counter, which will update independently as the components remember their own state:

"The convention is to name this pair like const [something, setSomething]. You could name it anything you like, but conventions make things easier to understand across projects." - React docs

What are Hooks?

Whenever you see a function in React starting with use (for example, useState, which is a built-in Hook), the syntax refers to something we call a "Hook" in React, allowing us to Hook into certain behaviors in React.

There are several built-in "Hooks" in React, and you can also create custom ones to meet your needs by combining existing Hooks.

Note: In this series, we won't cover creating custom Hooks or all of React's Hooks. Instead, we will focus on the ones you'll use 95% of the time.

Common mistake - regular variables

Let's look at a common mistake when people start using React, and that is trying to update variables directly.

Here's our counter code with a variable that we are trying to update:

const Counter = () => {
  let count = 0;
  return (
    <div>
      <button
        onClick={() => {
          count + 1;
        }}
      >
        Clicked {count} times
      </button>
    </div>
  );
};

This won't work for 2 reasons:

1) Local variables don’t persist after rerenders. If we render this component a second time, it doesn’t consider any changes to the local variables, which are reset to their original values. 2) Changes to local variables won’t trigger renders. React doesn’t realize it needs to update the component again with the new data and behaves as if nothing happened.

This is why we must use the useState value since it persists after a rerender and calling the update state function tells the component it needs to be updated.

Homework

Create your own CodeSandbox here and create your own counter component from scratch.

What's next?

In the next article, we will look at how we can pass props to a component to make them much more reusable.

You can read it here.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

FrontendReactjsTutorialJavaScriptLibrary
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.