DEV Community

Cover image for 📝 Understanding State in React: A Beginner’s Guide
mona fakhri
mona fakhri

Posted on

📝 Understanding State in React: A Beginner’s Guide

When building interactive web applications with React, one of the most important concepts you’ll encounter is state. State allows your components to “remember” information and update dynamically when something changes — for example, when a user clicks a button.

🔹 What is State?

In React, state is an object that stores data about a component. When the state changes, React automatically re-renders the component to reflect the updated data on the screen.

Think of state as a component’s “memory.”

🔹 Using the useState Hook

The most common way to manage state in functional components is with the useState hook.

Here’s a simple example:

`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;
`
Enter fullscreen mode Exit fullscreen mode

** Explanation: **

useState(0) → initializes the state variable count with a value of 0.

count → holds the current state.

setCount → function to update the state.

When you click the button, setCount increases count by 1, and React re-renders the component.

🔹 State vs. Props

Props: Data passed into a component from its parent.

State: Data managed inside the component itself.

In short:
Props = external input
State = internal memory

🔹 Key Rules of State

  1. Never modify state directly. Always use the updater function (setCount).

  2. State updates are asynchronous. Don’t rely on state updating immediately after calling setCount.

Top comments (0)