Register to get access to free programming courses with interactive exercises

useState Hook JS: React Hooks

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

  1. Introducing Hooks

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

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.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

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.