What is React State in React

This article provides a clear and concise overview of React state, explaining its fundamental role in building dynamic user interfaces. You will learn what state is, how it differs from props, and how to implement it in functional components using the useState hook. By the end of this guide, you will understand how state management triggers component re-renders to keep your UI in sync with user interactions.

Understanding React State

In React, state is a built-in JavaScript object used to store data or information about a component. The state of a component represents its current condition or “status.” Unlike regular variables, when state data changes, React automatically re-renders the component to update the user interface (UI) to reflect those changes.

State makes components dynamic and interactive. Common examples of state include: * Whether a dropdown menu is open or closed. * The text currently typed into an input form. * The current score in a game. * Shopping cart items in an e-commerce store.

React State vs. Props

While both state and props hold data that influences what is rendered on the screen, they serve different purposes:

How to Use State in Functional Components

In modern React, state is managed in functional components using the useState Hook. To use it, you must first import it from the React library.

Here is a simple example of a counter component utilizing state:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable named "count" initialized to 0
  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;

How the useState Hook Works:

  1. useState(0): This initializes the state variable with a starting value of 0.
  2. count: This variable holds the current value of the state.
  3. setCount: This is the updater function used to change the state value.
  4. Re-rendering: When the button is clicked, setCount(count + 1) is called. React updates the count variable and automatically re-renders the Counter component so the updated number displays on the screen.

Key Rules of React State

To ensure your React applications run efficiently, keep these rules in mind: