Register to get access to free programming courses with interactive exercises

useState Hook JS: React Hooks

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' }]);
  // ...
};

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

Hexlet Experts

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

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

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.