0
0
ReactConceptBeginner · 3 min read

What is State in React: Explanation and Example

In React, 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.

javascript
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;
Output
You clicked 0 times [Button labeled 'Click me']
🎯

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 useState hook to add state in functional components.
  • State is local to the component unless passed down as props.

Key Takeaways

State stores data that changes and controls what the component shows.
Use the useState hook to create and update state in React components.
Updating state triggers React to refresh the UI automatically.
State is best for data that affects rendering and user interaction.
Keep state local unless you need to share it with other components.