UseState
UseState
The React useState Hook allows us to track state in a function component.
Another Words useState is a React Hook that lets you add a state variable to your component.
State generally refers to data or properties that need to be tracking in an application.
Import useState
To use the useState Hook, we first need to import it into our component.
Example:
At the top of your component, import the useState Hook.
import { useState } from "react";Notice that we are destructuring useState from react as it is a named export.
Initialize useState
We initialize our state by calling useState in our function component.
useState accepts an initial state and returns two values:
The current state.During the first render, it will match the
initialStateyou have passed.A function that updates the state.
Example:
Initialize state at the top of the function component.
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("red");
}Notice that again
we are destructuring the returned values from
useState.The first value,
color, is our current state.The second value,
setColor, is the function that is used to update our state.These names are variables that can be named anything you would like.
Lastly, we set the initial state to "red":
useState("red").
set functions, like setSomething(nextState)
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:
const [name, setName] = useState('Edward');
function handleClick() {
setName('Taylor');
setAge(a => a + 1);Parameters
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.
Returns
set functions do not have a return value.
Caveats
The
setfunction only updates the state variable for the next render. If you read the state variable after calling thesetfunction, you will still get 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 anObject.iscomparison, 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. It updates the screen after all the event handlers have run and have called their
setfunctions. 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 useflushSync.The
setfunction has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. Learn more about removing Effect dependencies.Calling the
setfunction 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.In Strict Mode, React will call your updater function twice in order to help you find accidental impurities. 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
Adding state to a component
Call useState at the top level of your component to declare one or more state variables.
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.
useState returns an array with exactly two items:
The current state of this state variable, initially set to the initial state you provided.
The
setfunction 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:
function handleClick() {
setName('Robin');
}React will store the next state, render your component again with the new values, and update the UI.
