DEV Community

Cover image for What is useState in ReactJS?
Kyaw Min Tun
Kyaw Min Tun

Posted on

What is useState in ReactJS?

In ReactJS, useState is a Hook that allows you to add state management to functional components. Before Hooks were introduced, state could only be managed in class components, but useState enables functional components to also handle state.

How useState Works:

  • Syntax:
  const [state, setState] = useState(initialState);
Enter fullscreen mode Exit fullscreen mode
  • state: This is the current state value.
  • setState: This is a function that allows you to update the state.
  • initialState: This is the initial value of the state. It can be a primitive value, object, array, etc.

Example:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable called 'count' with an initial value of 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Initially, count is set to 0 (the initialState).
  • When the button is clicked, setCount is called, which updates the count state by incrementing it by 1.
  • The component re-renders with the updated count value.

Key Points:

  • State Preservation: React preserves the state between re-renders, so the component will remember the state value even after it re-renders.
  • Multiple State Variables: You can call useState multiple times in a single component if you need more than one piece of state.

Hooks like useState enable more complex stateful logic in functional components, making them a powerful alternative to class components.

Top comments (0)