> For the complete documentation index, see [llms.txt](https://edrus.gitbook.io/mt-it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://edrus.gitbook.io/mt-it/2nd-month/week-7/react-js/hooks/usestate.md).

# useState

useState is a React Hook that lets you add a state variable to your component.  const \[state, setState] = useState(initialState);

#### `useState(initialState)`  <a href="#usestate" id="usestate"></a>

Call `useState` at the top level of your component to declare a [state variable.](https://react.dev/learn/state-a-components-memory)

```jsx
import { useState } from 'react';

function MyComponent() {
  const [age, setAge] = useState(28);
  const [name, setName] = useState('Taylor');
  const [todos, setTodos] = useState(() => createTodos());
  // ...
```

The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment)

[See more examples below.](https://react.dev/reference/react/useState#usage)

**Parameters**&#x20;

* `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render.
  * If you pass a function as `initialState`, it will be treated as an *initializer function*. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. [See an example below.](https://react.dev/reference/react/useState#avoiding-recreating-the-initial-state)

**Returns**&#x20;

`useState` returns an array with exactly two values:

1. The current state. During the first render, it will match the `initialState` you have passed.
2. The [`set` function](https://react.dev/reference/react/useState#setstate) that lets you update the state to a different value and trigger a re-render.

**Caveats**&#x20;

* `useState` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* In Strict Mode, React will **call your initializer function twice** in order to [help you find accidental impurities.](https://react.dev/reference/react/useState#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your initializer function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.

***

#### `set` functions, like `setSomething(nextState)`  <a href="#setstate" id="setstate"></a>

The `set` function returned by `useState` lets you update the state to a different value and trigger a re-render. You can pass the next state directly, or a function that calculates it from the previous state:

```jsx
const [name, setName] = useState('Edward');

function handleClick() {
  setName('Taylor');
  setAge(a => a + 1);
  // ...
```

**Parameters**&#x20;

* `nextState`: The value that you want the state to be. It can be a value of any type, but there is a special behavior for functions.
  * If you pass a function as `nextState`, it will be treated as an *updater function*. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. [See an example below.](https://react.dev/reference/react/useState#updating-state-based-on-the-previous-state)

**Returns**&#x20;

`set` functions do not have a return value.

**Caveats**&#x20;

* The `set` function **only updates the state variable for the&#x20;*****next*****&#x20;render**. If you read the state variable after calling the `set` function, [you will still get the old value](https://react.dev/reference/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value) that was on the screen before your call.
* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn’t affect your code.
* React [batches state updates.](https://react.dev/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](https://react.dev/reference/react-dom/flushSync)
* Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example below.](https://react.dev/reference/react/useState#storing-information-from-previous-renders)
* In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.](https://react.dev/reference/react/useState#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.

***

### Usage  <a href="#usage" id="usage"></a>

#### Adding state to a component  <a href="#adding-state-to-a-component" id="adding-state-to-a-component"></a>

Call `useState` at the top level of your component to declare one or more [state variables.](https://react.dev/learn/state-a-components-memory)

```jsx
import { useState } from 'react';

function MyComponent() {
  const [age, setAge] = useState(42);
  const [name, setName] = useState('Taylor');
  // ...
```

The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment)

`useState` returns an array with exactly two items:

1. The current state of this state variable, initially set to the initial state you provided.
2. The `set` function that lets you change it to any other value in response to interaction.

To update what’s on the screen, call the `set` function with some next state:

```jsx
function handleClick() {
  setName('Robin');
}
```

React will store the next state, render your component again with the new values, and update the UI.

#### Pitfall

Calling the `set` function [**does not** change the current state in the already executing code](https://react.dev/reference/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value):

```jsx
function handleClick() {
  setName('Robin');
  console.log(name); // Still "Taylor"!
}
```

It only affects what `useState` will return starting from the *next* render.<br>

#### Updating state based on the previous state  <a href="#updating-state-based-on-the-previous-state" id="updating-state-based-on-the-previous-state"></a>

Suppose the `age` is `42`. This handler calls `setAge(age + 1)` three times:

```jsx
function handleClick() {
  setAge(age + 1); // setAge(42 + 1)
  setAge(age + 1); // setAge(42 + 1)
  setAge(age + 1); // setAge(42 + 1)
}
```

However, after one click, `age` will only be `43` rather than `45`! This is because calling the `set` function [does not update](https://react.dev/learn/state-as-a-snapshot) the `age` state variable in the already running code. So each `setAge(age + 1)` call becomes `setAge(43)`.

To solve this problem, **you may pass an&#x20;*****updater function*** to `setAge` instead of the next state:

```jsx
function handleClick() {
  setAge(a => a + 1); // setAge(42 => 43)
  setAge(a => a + 1); // setAge(43 => 44)
  setAge(a => a + 1); // setAge(44 => 45)
}
```

Here, `a => a + 1` is your updater function. It takes the pending state and calculates the next state from it.

React puts your updater functions in a [queue.](https://react.dev/learn/queueing-a-series-of-state-updates) Then, during the next render, it will call them in the same order:

1. `a => a + 1` will receive `42` as the pending state and return `43` as the next state.
2. `a => a + 1` will receive `43` as the pending state and return `44` as the next state.
3. `a => a + 1` will receive `44` as the pending state and return `45` as the next state.

There are no other queued updates, so React will store `45` as the current state in the end.

By convention, it’s common to name the pending state argument for the first letter of the state variable name, like `a` for `age`. However, you may also call it like `prevAge` or something else that you find clearer.

React may [call your updaters twice](https://react.dev/reference/react/useState#my-initializer-or-updater-function-runs-twice) in development to verify that they are [pure.](https://react.dev/learn/keeping-components-pure)

#### Updating objects and arrays in state  <a href="#updating-objects-and-arrays-in-state" id="updating-objects-and-arrays-in-state"></a>

You can put objects and arrays into state. In React, state is considered read-only, so **you should&#x20;*****replace*****&#x20;it rather than&#x20;*****mutate*****&#x20;your existing objects**. For example, if you have a `form` object in state, don’t mutate it:

```jsx
// 🚩 Don't mutate an object in state like this:
form.firstName = 'Taylor';
```

Instead, replace the whole object by creating a new one:

```jsx
// ✅ Replace state with a new object
setForm({reac
  ...form,
  firstName: 'Taylor'
});
```

Read [updating objects in state](https://react.dev/learn/updating-objects-in-state) and [updating arrays in state](https://react.dev/learn/updating-arrays-in-state) to learn more.

#### Avoiding recreating the initial state  <a href="#avoiding-recreating-the-initial-state" id="avoiding-recreating-the-initial-state"></a>

React saves the initial state once and ignores it on the next renders.

```jsx
function TodoList() {
  const [todos, setTodos] = useState(createInitialTodos());
  // ...
```

Although the result of `createInitialTodos()` is only used for the initial render, you’re still calling this function on every render. This can be wasteful if it’s creating large arrays or performing expensive calculations.

To solve this, you may **pass it as an&#x20;*****initializer*****&#x20;function** to `useState` instead:

```jsx
function TodoList() {
  const [todos, setTodos] = useState(createInitialTodos);
  // ...
```

Notice that you’re passing `createInitialTodos`, which is the *function itself*, and not `createInitialTodos()`, which is the result of calling it. If you pass a function to `useState`, React will only call it during initialization.

React may [call your initializers twice](https://react.dev/reference/react/useState#my-initializer-or-updater-function-runs-twice) in development to verify that they are [pure.](https://react.dev/learn/keeping-components-pure)

#### Resetting state with a key  <a href="#resetting-state-with-a-key" id="resetting-state-with-a-key"></a>

You’ll often encounter the `key` attribute when [rendering lists.](https://react.dev/learn/rendering-lists) However, it also serves another purpose.

You can **reset a component’s state by passing a different `key` to a component.** In this example, the Reset button changes the `version` state variable, which we pass as a `key` to the `Form`. When the `key` changes, React re-creates the `Form` component (and all of its children) from scratch, so its state gets reset.

Read [preserving and resetting state](https://react.dev/learn/preserving-and-resetting-state) to learn more.

#### Storing information from previous renders  <a href="#storing-information-from-previous-renders" id="storing-information-from-previous-renders"></a>

Usually, you will update state in event handlers. However, in rare cases you might want to adjust state in response to rendering — for example, you might want to change a state variable when a prop changes.

In most cases, you don’t need this:

* **If the value you need can be computed entirely from the current props or other state,** [**remove that redundant state altogether.**](https://react.dev/learn/choosing-the-state-structure#avoid-redundant-state) If you’re worried about recomputing too often, the [`useMemo` Hook](https://react.dev/reference/react/useMemo) can help.
* If you want to reset the entire component tree’s state, [pass a different `key` to your component.](https://react.dev/reference/react/useState#resetting-state-with-a-key)
* If you can, update all the relevant state in the event handlers.

In the rare case that none of these apply, there is a pattern you can use to update state based on the values that have been rendered so far, by calling a `set` function while your component is rendering.

Here’s an example. This `CountLabel` component displays the `count` prop passed to it:

```jsx
export default function CountLabel({ count }) {
  return <h1>{count}</h1>
}
```

Say you want to show whether the counter has *increased or decreased* since the last change. The `count` prop doesn’t tell you this — you need to keep track of its previous value. Add the `prevCount` state variable to track it. Add another state variable called `trend` to hold whether the count has increased or decreased. Compare `prevCount` with `count`, and if they’re not equal, update both `prevCount` and `trend`. Now you can show both the current count prop and *how it has changed since the last render*.

Note that if you call a `set` function while rendering, it must be inside a condition like `prevCount !== count`, and there must be a call like `setPrevCount(count)` inside of the condition. Otherwise, your component would re-render in a loop until it crashes. Also, you can only update the state of the *currently rendering* component like this. Calling the `set` function of *another* component during rendering is an error. Finally, your `set` call should still [update state without mutation](https://react.dev/reference/react/useState#updating-objects-and-arrays-in-state) — this doesn’t mean you can break other rules of [pure functions.](https://react.dev/learn/keeping-components-pure)

This pattern can be hard to understand and is usually best avoided. However, it’s better than updating state in an effect. When you call the `set` function during render, React will re-render that component immediately after your component exits with a `return` statement, and before rendering the children. This way, children don’t need to render twice. The rest of your component function will still execute (and the result will be thrown away). If your condition is below all the Hook calls, you may add an early `return;` to restart rendering earlier.

***

### Troubleshooting  <a href="#troubleshooting" id="troubleshooting"></a>

#### I’ve updated the state, but logging gives me the old value  <a href="#ive-updated-the-state-but-logging-gives-me-the-old-value" id="ive-updated-the-state-but-logging-gives-me-the-old-value"></a>

Calling the `set` function **does not change state in the running code**:

```jsx
function handleClick() {
  console.log(count);  // 0

  setCount(count + 1); // Request a re-render with 1
  console.log(count);  // Still 0!

  setTimeout(() => {
    console.log(count); // Also 0!
  }, 5000);
}
```

This is because [states behaves like a snapshot.](https://react.dev/learn/state-as-a-snapshot) Updating state requests another render with the new state value, but does not affect the `count` JavaScript variable in your already-running event handler.

If you need to use the next state, you can save it in a variable before passing it to the `set` function:

```jsx
const nextCount = count + 1;
setCount(nextCount);

console.log(count);     // 0
console.log(nextCount); // 1
```

***

#### I’ve updated the state, but the screen doesn’t update  <a href="#ive-updated-the-state-but-the-screen-doesnt-update" id="ive-updated-the-state-but-the-screen-doesnt-update"></a>

React will **ignore your update if the next state is equal to the previous state,** as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. This usually happens when you change an object or an array in state directly:

```jsx
obj.x = 10;  // 🚩 Wrong: mutating existing object
setObj(obj); // 🚩 Doesn't do anything
```

You mutated an existing `obj` object and passed it back to `setObj`, so React ignored the update. To fix this, you need to ensure that you’re always [*replacing* objects and arrays in state instead of *mutating* them](https://react.dev/reference/react/useState#updating-objects-and-arrays-in-state):

```jsx
// ✅ Correct: creating a new object
setObj({
  ...obj,
  x: 10
});
```

***

#### I’m getting an error: “Too many re-renders”  <a href="#im-getting-an-error-too-many-re-renders" id="im-getting-an-error-too-many-re-renders"></a>

You might get an error that says: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Typically, this means that you’re unconditionally setting state *during render*, so your component enters a loop: render, set state (which causes a render), render, set state (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler:

```jsx
// 🚩 Wrong: calls the handler during render
return <button onClick={handleClick()}>Click me</button>

// ✅ Correct: passes down the event handler
return <button onClick={handleClick}>Click me</button>

// ✅ Correct: passes down an inline function
return <button onClick={(e) => handleClick(e)}>Click me</button>
```

If you can’t find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `set` function call responsible for the error.

***

#### My initializer or updater function runs twice  <a href="#my-initializer-or-updater-function-runs-twice" id="my-initializer-or-updater-function-runs-twice"></a>

In [Strict Mode](https://react.dev/reference/react/StrictMode), React will call some of your functions twice instead of once:

```jsx
function TodoList() {
  // This component function will run twice for every render.

  const [todos, setTodos] = useState(() => {
    // This initializer function will run twice during initialization.
    return createTodos();
  });

  function handleClick() {
    setTodos(prevTodos => {
      // This updater function will run twice for every click.
      return [...prevTodos, createTodo()];
    });
  }
  // ...
```

This is expected and shouldn’t break your code.

This **development-only** behavior helps you [keep components pure.](https://react.dev/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and updater functions are pure, this shouldn’t affect your logic. However, if they are accidentally impure, this helps you notice the mistakes.

For example, this impure updater function mutates an array in state:

```jsx
setTodos(prevTodos => {
  // 🚩 Mistake: mutating state
  prevTodos.push(createTodo());
});
```

Because React calls your updater function twice, you’ll see the todo was added twice, so you’ll know that there is a mistake. In this example, you can fix the mistake by [replacing the array instead of mutating it](https://react.dev/reference/react/useState#updating-objects-and-arrays-in-state):

```jsx
setTodos(prevTodos => {
  // ✅ Correct: replacing with new state
  return [...prevTodos, createTodo()];
});
```

Now that this updater function is pure, calling it an extra time doesn’t make a difference in behavior. This is why React calling it twice helps you find mistakes. **Only component, initializer, and updater functions need to be pure.** Event handlers don’t need to be pure, so React will never call your event handlers twice.

Read [keeping components pure](https://react.dev/learn/keeping-components-pure) to learn more.

***

#### I’m trying to set state to a function, but it gets called instead  <a href="#im-trying-to-set-state-to-a-function-but-it-gets-called-instead" id="im-trying-to-set-state-to-a-function-but-it-gets-called-instead"></a>

You can’t put a function into state like this:

```jsx
const [fn, setFn] = useState(someFunction);

function handleClick() {
  setFn(someOtherFunction);
}
```

Because you’re passing a function, React assumes that `someFunction` is an [initializer function](https://react.dev/reference/react/useState#avoiding-recreating-the-initial-state), and that `someOtherFunction` is an [updater function](https://react.dev/reference/react/useState#updating-state-based-on-the-previous-state), so it tries to call them and store the result. To actually *store* a function, you have to put `() =>` before them in both cases. Then React will store the functions you pass.

```jsx
const [fn, setFn] = useState(() => someFunction);

function handleClick() {
  setFn(() => someOtherFunction);
}
```

<=======================================================================>

### SIMPLE STATE IN REACT <a href="#simple-state-in-react" id="simple-state-in-react"></a>

In the past, state couldn't be used in function components. Hence they called them functional stateless components. However, with the release of React Hooks, state can be used in this kind of component too, and so they were rebranded by the React community to function components. A straightforward example on how to use state in a function component with the useState hook is demonstrated in the following example:

```jsx
const App = () => {
  const [count, setCount] = React.useState(0);
  const handleIncrease = () => {
    setCount(count + 1);
  };
  const handleDecrease = () => {
    setCount(count - 1);
  };
  return (
    <div>
      {" "}
      Count: {count} <hr />{" "}
      <div>
        {" "}
        <button type="button" onClick={handleIncrease}>
          {" "}
          Increase{" "}
        </button>{" "}
        <button type="button" onClick={handleDecrease}>
          {" "}
          Decrease{" "}
        </button>{" "}
      </div>{" "}
    </div>
  );
};

```

The useState function takes as argument a value for the initial state. In this case, the count starts at 0. In addition, the hook returns an array of two values: `count` and `setCount`. It's up to you to name the two values, because they are [destructured from the returned array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) where renaming is allowed.

The first value, in this case `count`, represents the current state. The second value, in this case `setCount`, is a function to update the state with anything that's passed to this function when calling it. This function is also called the state update function. Every time this function is called, React re-renders the component to render the new state.

You can also read this [article, if you want to know how state management has changed from class components to function components](https://www.robinwieruch.de/react-hooks-migration/) in case you are dealing with class components as well.

That's everything you need to know to get started with simple state management in React. If you are interested about React's useState caveats for growing React applications, then continue to read.

### COMPLEX STATE IN REACT <a href="#complex-state-in-react" id="complex-state-in-react"></a>

So far, the example has only shown useState with a JavaScript primitive. That's where useState shines. It can be used for integers, booleans, strings, and also arrays. However, once you plan to manage more complex state with objects or more complex arrays, you should check out [React's useReducer hook](https://www.robinwieruch.de/react-usereducer-hook/). There are various scenarios where useReducer outperforms useState:

* complex state containers
* complex state transitions
* conditional state updates

It also helps to avoid multiple successive state updates by using only useState. You should definitely check it out if you want to manage more complex state in React.

### ASYNCHRONOUS STATE IN REACT <a href="#asynchronous-state-in-react" id="asynchronous-state-in-react"></a>

What happens if you are dependent on actual state to update the state? Let's illustrate this case with an example where we are delaying the state update with a [JavaScript built-in setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) function:

```jsx
const App = () => {
  const [count, setCount] = React.useState(0);
  const handleIncrease = () => {
    setTimeout(() => setCount(count + 1), 1000);
  };
  const handleDecrease = () => {
    setTimeout(() => setCount(count - 1), 1000);
  };
  return (
    <div>
      {" "}
      Count: {count} <hr />{" "}
      <div>
        {" "}
        <button type="button" onClick={handleIncrease}>
          {" "}
          Increase{" "}
        </button>{" "}
        <button type="button" onClick={handleDecrease}>
          {" "}
          Decrease{" "}
        </button>{" "}
      </div>{" "}
    </div>
  );
};

```

Every time you click on one of the buttons, the state update function is called with a delay of one second. That works for a single click. However, try to click one of the buttons multiple times in a row. The state update function will always operate on the same state (here: `count`) within this one second. In order to fix this problem, you can pass a function to the state update function from useState:

```jsx
import React from "react";
const App = () => {
  const [count, setCount] = React.useState(0);
  const handleIncrease = () => {
    setTimeout(() => setCount((state) => state + 1), 1000);
  };
  const handleDecrease = () => {
    setTimeout(() => setCount((state) => state - 1), 1000);
  };
  return (
    <div>
      {" "}
      Count: {count} <hr />{" "}
      <div>
        {" "}
        <button type="button" onClick={handleIncrease}>
          {" "}
          Increase{" "}
        </button>{" "}
        <button type="button" onClick={handleDecrease}>
          {" "}
          Decrease{" "}
        </button>{" "}
      </div>{" "}
    </div>
  );
};
export default App;

```

The function offers you the state at the time of executing the function. This way, you never operate on any stale state. Therefore, a good rule of thumb may be: always use a function in useState's update function if your state update depends on your previous state.

***

React's useState is the go-to hook to manage state. It can be used [with useReducer and useContext](https://www.robinwieruch.de/react-state-usereducer-usestate-usecontext/) for modern state management in React. [Compared to useReducer, it is the more lightweight approach to manage state.](https://www.robinwieruch.de/react-usereducer-vs-usestate/)

<br>
