The useState()
hook works with the state inside components.
Unlike class components, hooks do everything at once: initialization, updating, and providing access to the state. Let us observe a call, for example:
// Don't forget to import
import React, { useState } from 'react';
const Example = () => {
// We have chosen the names of the returned values 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_intro-1 by Hexlet (@hexlet) on CodePen.
The useState()
hook takes the initial state as input and returns an array of two values:
- The current state value
- A function that updates the state
This code looks unusual, so there are still questions 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
value will always be 0
because we are constantly calling useState()
.
Strange as it may seem, this won't happen. Hooks are much funkier than they seem at first glance. Yes, we call the useState()
function every re-rendering occurs, but it knows about it internally and considers it in its work. We set the initial state and do not use it further. The state itself is stored somewhere inside, 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:
- In a callback, as in the example above
- In another component to which we can pass this function
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' }]
We can use hooks 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' }]);
// ...
};
How many state variables should you create?
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 });
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
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.