The useState()
hook is responsible for working with the state inside components. Unlike class components, hooks do everything at once: initialization, updating and providing access to the state. Example of a call:
// Don't forget to import
import React, { useState } from 'react';
const Example = () => {
// The names of the returned values are chosen arbitrarily
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} time(s)</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
};
See the Pen js_react_hooks_use_effect-1 by Hexlet (@hexlet) on CodePen.
useState()
takes the initial state as input and returns an array of two values: the current state value and a function that updates the state. Going past the fact that this code looks unusual, there are still questions to be asked about its operation. As we know, the component, as a function, is called for each re-rendering, and it's logical to assume that the count
count value will always be 0
due to the fact we're constantly calling useState()
. Strange as it may seem, this won't happen. Hooks are much funkier than it seems at first glance. Yes, the useState()
function is indeed called every re-rendering occurs, but it knows about it internally, and takes it into account in its work. The initial state is set exactly once and isn't used further. The state itself is stored somewhere inside and is hidden from direct change. The only way to influence it is to call the returned function and pass a new state.
The setCount()
function can be called anywhere, for example in a callback, as in the example above, or in another component that this function can be passed to. In this sense, everything works the same as in classes.
Unlike this.setState()
, the useState()
hook does not merge the old state with the new one:
// Somewhere in the callback
setTodos([{ text: 'Wash the dishes' }]);
// In the next loop
// The initial value is missing
console.log(todos); // => [{ text: 'Wash the dishes' }]
Hooks can be used more than once if needed. We can easily create multiple state variables:
const ExampleWithManyStates = () => {
const [age, setAge] = useState(42);
const [schoolName, setSchoolName] = useState('Hexlet');
const [todos, setTodos] = useState([{ text: 'Learn hooks' }]);
// ...
};
Technically, we can put everything in one variable, as we did with classes, but with hooks there isn't much need for this. Moreover, the state within a single component is easier to manage when it's divided into parts that are updated together. For example:
const [position, setPosition] = useState({ left: 0, top: 0 });
const [size, setSize] = useState({ width: 100, height: 100 });
The Hexlet support team or other students will answer you.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
From a novice to a developer. Get a job or your money back!
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.