A guide to useState in React
The useState hook lets you add state to function components.
By calling React.useState inside a function component
Here I am, writing a React hooks tutorial for you. I decided to wait until hooks got finally released before dropping this post. Together we'll learn React hooks step by step, with a look at how the same logic would be implemented with ES6 classes.
React Hooks Tutorial for Beginners: what you will learn
In the following tutorial you'll learn:
React Hooks Tutorial for Beginners: requirements
To follow along with the tutorial you should have a basic understanding of:
React Hooks Tutorial for Beginners: setting up the project
If you want to follow along with the examples make sure to configure a React development environment. Run:
npx create-react-app exploring-hooks
(You should have one of the latest version of Node.js for running npx).
What Does the React.useState Hook Do?
The useState hook lets you add state to function components.
By calling React.useState inside a function component, you create a single piece of state associated with that component. (every hook starts with the word “use”; a call to useState literally lets you “use state” in a function component)
In classes, the state was always an object, and you could store multiple values on that object.
But with hooks, the state can be any type you want – you can useState with an array, useState an object, a number, a boolean, a string, whatever you need. Each call to useState creates a single piece of state, holding a single value of any type.
Show/Hide a Component (useState with a boolean)
This example is a component that displays some text with a “read more” link at the end, and will expand to show the rest of the text when the link is clicked.
Or if you’re more the video type, watch me build a similar component here:
Read through the comments to see what’s happening here:
// First: import useState. It's a named export from 'react'
// Or we could skip this step, and write React.useState
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
// This component expects 2 props:
// text - the text to display
// maxLength - how many characters to show before "read more"
function LessText({ text, maxLength }) {
// Create a piece of state, and initialize it to `true`
// `hidden` will hold the current value of the state,
// and `setHidden` will let us change it
const [hidden, setHidden] = useState(true);
// If the text is short enough, don't bother with the
// buttons
if (text.length <= maxLength) {
return <span>{text}</span>;
}
// Render the text (shortened or full-length) followed by
// a link to expand/collapse it.
// When a link is clicked, update the value of `hidden`,
// which will trigger a re-render
return (
<span>
{hidden ? `${text.substr(0, maxLength).trim()} ...` : text}
{hidden ? (
<a onClick={() => setHidden(false)}> read more</a>
) : (
<a onClick={() => setHidden(true)}> read less</a>
)}
</span>
);
}
ReactDOM.render(
<LessText
text={`Focused, hard work is the real key
to success. Keep your eyes on the goal,
and just keep taking the next step
towards completing it.`}
maxLength={35}
/>,
document.querySelector('#root')
);
With just this one line of code, we’ve made this function stateful:
const [hidden, setHidden] = useState(true);
Once that’s done, the “read more” / “read less” links just need to call setHidden when they’re clicked.
useState returns an array with 2 elements, and we’re using ES6 destructuring to assign names to them. The first element is the current value of the state, and the second element is a state setter function – just call it with a new value, and the state will be set and the component will re-render.
const [hidden, setHidden] = useState(true);
But what is this function doing, really? If it gets called every render (and it does!), how can it retain state?
useState is a Hook (function) that allows you to have state variables in functional components.
You pass the initial state to this function, and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.