React State

What is State in React?

Each component in React has some data in it and is available in the form of an object. state refers to that built-in object in the component and is used to set or modify data within the component. With state, we can keep track of changing information that needs to be displayed by the component, or interacted with by the user. Each component in React can have its own state, and it changes to the state trigger re-renders to update the UI.


Why is State Important in a React Application?

  • Dynamic Updates: State allows React components to render dynamic and interactive user interfaces based on the current data in the state.
  • Reactivity: When the state changes, React automatically re-renders the component, ensuring that the UI stays in sync with the application logic.
  • Isolation: State is scoped to individual components. This makes it easier to manage specific parts of an application.

How to Define State?

In functional components, the useState hook is used to define state. The useState hook returns an array with two elements:

  • The current state value.
  • A function to update the state.

For example, in the following statement, useState() creates a state with an initial state value of 0. count is used to read the state, and setCount function is used to update the state.

</>
Copy
const [count, setCount] = useState(0);

Example: Defining State

In the following React application, we defined a state, and displayed the data in that state to UI using JSX.

App.js

</>
Copy
import React, { useState } from 'react';

function Counter() {
  // Define state with initial value 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Current Count: {count}</p>
    </div>
  );
}

export default Counter;

Output: