DEV Community

Chris Blakely
Chris Blakely

Posted on • Originally published at jschris.com

What is Reacts useState hook? 4 common examples you'll need to know

Originally posted at jschris.com

What is the useState hook?

Before we get into it, its a good idea to have a look what the useState hook is. In a nutshell:

the useState hooks lets us store "state" as data, which our functional components can use

In other words, when you have things that can change on your UI, you can store it in state. React then "reacts" and rerenders your components when the state changes. Cool right? The useState hook looks like this:

const [number, setNumber] = useState(5);

The useState "hook" is just a function call:

useState(5);

This function gives us back an array. We use array destructuring to get 2 things out of the array:

  • A variable that holds the current value of the state object (in this case, it's called number)
  • A function that lets us update the state variable (in this case, its called setNumber)

I've called these things number and setNumber but you can name them whatever you want. It's a good idea to name them similar to what they represent, and the function to update the state value should be prefixed with "set" like so:

const [name, setName] = useState('Chris');
const [age, setAge] = useState(28);

You may notice I am passing some values ("Chris" and the number 28) to these state objects. This is how we set an initial state. This is optional, you don't have to set an initial state if you don't want to.

Once we've setup state, we can change the state value using the setter function like so:

const [name, setName] = useState('Chris');
const [age, setAge] = useState(28);

setName('Chris McNew Name');
setAge(29);

This will update our state values, causing React to rerender our components with the new values.

We can store a number of different things in state, depending on how you want to represent the data on your UI:

  • Strings
  • Numbers
  • Booleans
  • Objects
  • Arrays

Now that we've learned what is the useState hook is, let's look at 5 common examples you'll need to know when using the useState hook!

1. Showing/hiding things

Number 1 on our list is showing and hiding things. This can be a range of things:

  • Showing and hiding a modal
  • Showing a loading spinner
  • Toggling the display of a component

Let's look at an example where if the user clicks a button, the text "This text will show" will appear on the page:

import React, { useState } from 'react';

export default function App() {
    const [showText, setShowText] = useState(false);

    return (
        <div className='App'>
            <button onClick={() => setShowText(!showText)}>Toggle Text</button>

            {showText && <div>This text will show!</div>}
        </div>
    );
}

We have a state object:

const [showText, setShowText] = useState(false);

This is to indicate wether the text should show or not. In other words, this holds the state of the text, which will either be shown/or hidden.

We then have some logic around the component we want to show based on this:

{
    showText && <div>This text will show!</div>;
}

This basically reads as if showText is true, render the JSX. So since showText is initally false, the text won't appear. If you initialised the showText state object to be true, the text would appear.

Having to manually change code to show and hide the text isn't the best user experience, so let's look at how we can show/hide this component using a button click. When the button is clicked, it will change the state to the opposite of what it was previously:

<button onClick={() => setShowText(!showText)}>Toggle Text</button>

Notice we use the setShowText function along with a lovely inline arrow function to change the state when the button is clicked. This sets it to the opposite of what it currently is. When this changes, the component rerenders, and displays the text based on the new showText value.

2. Conditional Rendering

Similar to showing and hiding things, we can conditionally render based on a state value. Lets take the example of a logged in user. If a user goes to our app who isn't logged in, we want to show them the "Sign in" screen. If they are logged in, we want to show them the "Dashboard":

import React, { useState } from 'react';

function SignInScreen() {
    return <div>Please login!</div>;
}

function DashboardScreen() {
    return <div>Hello! Welcome to your dashboard</div>;
}

export default function App() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    return <div className='App'>{isLoggedIn ? <DashboardScreen /> : <SignInScreen />}</div>;
}

Firstly, we store a value called isLoggedIn in state. This tells us if the user is logged in or not. Next, we use the ternary operator to decide which component to render:

isLoggedIn ? <DashboardScreen /> : <SignInScreen />;

This means "if logged in is true, show the DashboardScreen component. Else, show the SignInScreen component.

In a fully fledged app, the "SignInScreen" component would do some stuff to log the user in and then change the isLoggedIn state value to true. This would rerender the component App component and the user will be shown the Dashboard. Hurray!

3. Holding a list of data

Quite often you'll need to display a list of data in your app (did someone say TODO LIST?). To do this, you can store the list in state, and render each item in the list as a component:

import React, { useState } from 'react';

export default function App() {
    const [todos, setTodos] = useState([
        { description: 'First thing on the list', isComplete: false },
        { description: 'Second thing on the list', isComplete: false },
        { description: 'Last thing todo', isComplete: false },
    ]);

    return (
        <>
            {todos.map((todo) => (
                <div>
                    Description:
                    {todo.description} - Completed:
                    {todo.isComplete.toString()}
                </div>
            ))}
        </>
    );
}

Notice how we initialised the state value with our data - in this case it's an array of objects. Each object holds some information about a Todo item - the items description and whether the item is completed or not.

We then use the map function to iterate over the todos state object and display the description and whether it is completed or not to the screen.

Since we stored this data in state, if the list changes in any way, such as if we removed or added an item, this would trigger a state change and update the component with the new list.

4. Holding form values

Working with forms can be a pain, luckily for us using React hooks makes it easier. Let's say we have a simple login form, when the user logs in and alert pops up showing the information they enter. OK so I never said it was a very good login form. Anyways...

import React, { useState } from 'react';

export default function App() {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");

    const handleFormSubmit = () => {
        alert(`username is ${username}, password is ${password}`);
    };

    return (
        <>
            <form onSubmit={handleFormSubmit}>
                Username:
                <input value={username} onChange={(e) => setUsername(e.target.value)} />
                Password:
                <input value={password} onChange={(e) => setPassword(e.target.value)} />
                <button type='submit'>Submit</button>
            </form>
        </>
    );
}

Our form has 2 values, each of which has their own state value. Whenever the user types into a form field, we change the state value for that form field. Since we have quick access to the form field values, we can perform other logic easily, such as validation in the handleFormSubmit function:

const handleFormSubmit = () => {
    if (!username || !password) {
        alert(`Please enter a username and password!`);
    }
};

Want to try putting these ideas into action?

Why not try building some React projects to boost your learning even further? I send out project ideas every few weeks(ish) with project ideas, starter code, and tips. Subscribe to get this straight to your inbox!

Top comments (0)