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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay