State and useState in React


1. What is State?

In React, state is a way to store data that can change over time and affect what’s rendered on the screen.

  • Think of it as a “memory” for your component.
  • When state changes, React automatically re-renders the component with the new value.

2. What is useState?

useState is a React Hook that lets you add state to functional components.

Syntax:

const [stateVariable, setStateFunction] = useState(initialValue);
  • stateVariable: The current value of the state.
  • setStateFunction: A function used to update the state.
  • initialValue: The initial value of the state.

3. Example: Counter Component

Here’s a simple example of a counter:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable called "count", initial value is 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

export default Counter;

Explanation:

  1. const [count, setCount] = useState(0);
    • count is the state variable.
    • setCount updates the value of count.
    • 0 is the initial value.
  2. When you click Increment, setCount(count + 1) updates the state.
  3. React re-renders the component, and the new count is displayed.

Key Points:

  • State is local to the component.
  • Updating state causes the component to re-render.
  • useState works only in functional components, not class components.

Leave a Reply