Understanding State in React: Why It's Needed and How to Use useState

What is State in React?

State in React is a way to manage and store data within a component that can change over time. It allows components to create and maintain their own data, which can affect how they render and behave.

Simple Explanation:

  • Think of state as a box that holds information about a component.

  • Whenever the data inside that box changes, React re-renders the component to reflect those changes.

For example, if you're building a counter app, the current count value is stored in the component's state. When you increase or decrease the count, the state updates, and the UI re-renders to show the new count.

Why is State Needed?

  1. Dynamic UI: State allows your application to respond to user actions and change what the user sees on the screen.

  2. User Interaction: It helps track user inputs, selections, and other interactive elements, like form fields, buttons, etc.

  3. Component Communication: State can also help components communicate and share data effectively within the application.

How to Achieve State with useState

React provides a built-in hook called useState to manage state in functional components. Here's how to use it:

  1. Import useState from React.

  2. Initialize State: Call useState with an initial value. It returns an array containing the current state and a function to update it.

  3. Update State: Use the updater function to change the state when needed, which will automatically re-render the component.

Example: Counter Component

import React, { useState } from 'react';

function Counter() {
  // Step 1: Initialize state
  const [count, setCount] = useState(0); // Initial count is 0

  // Step 2: Create a function to update the state
  const increment = () => {
    setCount(count + 1); // Update the count state
  };

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increase Count</button>
    </div>
  );
}

export default Counter;

Breakdown of the Example:

  • const [count, setCount] = useState(0);: This line initializes the state variable count with a value of 0. setCount is the function used to update count.

  • setCount(count + 1);: This function updates the state by incrementing the current value of count by 1 whenever the button is clicked.

  • When the button is clicked, the count updates, and React re-renders the Counter component to display the new count.

In Summary:

  • State in React is a way to manage data within a component that can change over time.

  • It is essential for creating dynamic and interactive user interfaces.

  • You can manage state in functional components using the useState hook, allowing you to initialize, read, and update state easily.

2
Subscribe to my newsletter

Read articles from Aravind Kishore Peerla directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aravind Kishore Peerla
Aravind Kishore Peerla