What is State in React: Explanation and Example
state is a way to store and manage data that changes over time within a component. It allows components to remember information and update the user interface automatically when that data changes.How It Works
Think of state in React like a component's personal notebook where it writes down information it needs to remember. When this information changes, React automatically updates what you see on the screen to match the new data.
For example, if you have a button that counts how many times it was clicked, the count number is stored in state. Each click updates the notebook, and React redraws the number so you see the latest count.
This process helps keep the user interface in sync with the data without you having to manually change the display.
Example
This example shows a simple counter that increases when you click the button. The count is stored in state and updates the screen automatically.
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } export default Counter;
When to Use
Use state when you need to keep track of information that changes and affects what the user sees. Common examples include:
- Form inputs where users type data
- Toggle switches or buttons that change appearance
- Loading indicators that show progress
- Dynamic lists that update when items are added or removed
State helps your app respond to user actions and keep the interface fresh and interactive.
Key Points
- State holds data that can change over time in a component.
- Changing state causes React to update the UI automatically.
- Use the
useStatehook to add state in functional components. - State is local to the component unless passed down as props.