DEV Community

Cover image for useState( )
akanoob
akanoob

Posted on

useState( )

The useState() hook in React allows functional components to manage state. It returns a state variable and a function to update it. You initialize state with an initial value, and updating it triggers re-rendering. You can manage multiple state variables in a component. Always use the setter function to update state for React's efficiency.

const [state, setState] = useState(initialValue);
Here, state is the current value of the state variable, and setState is a function that allows you to update state.

  • setState(newValue);
  • setState(prevState => prevState + 1);

simple React component that implements a counter using the useState() hook:

import React, { useState } from 'react';

function Counter() {
  // Define a state variable 'count' and a function 'setCount' to update it
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Counter</h2>
      <p>Count: {count}</p>
      {/* Button to increment count */}
      <button onClick={() => setCount(count + 1)}>Increment</button>
      {/* Button to decrement count */}
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

export default Counter;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)