DEV Community

Cover image for Master React useState()
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Master React useState()

useState()
useState() is a React Hook that allows functional components to store and manage state.State represents information that can change while the application is running, such as:

  • Counter value
  • User input
  • Theme (Light/Dark)
  • Login status
  • Like button count Without useState(), these values cannot update the UI dynamically. Syntax
const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

state → Stores the current value.
setState → Updates the value.
initialValue → The default value when the component loads.
Why do we use useState() in React?
We use useState() to store and update data that can change inside a React component. When the state changes, React automatically updates the UI without refreshing the entire page.Without useState(), variables don't make React re-render the component when their values change.
Using a normal variable

function App() {
  let count = 0;

  const increment = () => {
    count++;
    console.log(count);
  };

  return (
    <>
      <h1>{count}</h1>
      <button onClick={increment}>Increment</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Even though count increases in the console, the UI still shows 0 because React doesn't know the variable changed.
Using useState()

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now, every time you click the button:

  • setCount() updates the state.
  • React detects the change.
  • The component re-renders.
  • The UI shows the latest value.

Re-rendering
Re-rendering means React runs the component again and updates the UI whenever its state or props change.React re-renders when:
State changes (useState)
Props change
Parent component re-renders (its child components may also re-render)

Top comments (0)