up:: [[React MOC]]
tags:: #note/develop #on/computing/programming
# React State
In [[React MOC|React]] components, local variables don't persist between renders and don't trigger renders. To update a component with new data, we need something that will persist between renders and trigger them.
A *state variable* is a variable inside a component that persists between renders. When a state variable is changed, it triggers a render.
## The `useState()` Hook
`useState()` is a React [[React Hooks|hook]] that allows you to create state variables. Here is an example of using the hook:
```jsx
import { useState } from "react";
const App = () => {
const [count, setCount] = useState(0);
return (
<h1>{count}</h1>
);
};
```
The `useState()` hook always returns an array with two items: the initialized state variable and a setter function used to update the variable. Here we use array destructuring to extract the variable and function.
The argument passed to `useState()` is the initial value for the variable. To change the variable's value, pass the new value to the setter function. In this case, that would be `setCount()`.
Note that you **must** use the setter function to properly update the value of the state variable.
State is local to component instances. If you render the same component twice, each copy will have its own separate state.
## References
“State: A Component’s Memory – React.” Accessed March 14, 2024. [https://react.dev/learn/state-a-components-memory](https://react.dev/learn/state-a-components-memory).