Search⌘ K

useState

Explore how to use the React useState Hook to initialize and update component state. Understand different update patterns for primitive values, arrays, and objects along with best practices to avoid unnecessary renders and state replacement behavior.

Initializing the state

This Hook returns a value as well as a function to us, which we can use to update the value. We can initialize the state using this Hook in the following way:

const [state, setState] = useState(initialState);

During the first rendering of a component that uses this Hook, this value is equal to the initialState that you pass to the state. If the parameter that has been passed in is a function, it will use the return value of the function as its initial value.

Updating the state

When the update function is called, React ensures that the function always has the same identity and does not create a new function whenever the Hook is called. This is important because it reduces the number of ...