React useState Hook

React‘s useState hook is a built-in function that allows you to add state to functional components. Prior to the introduction of hooks, you could only use state in class components. With useState, you can use stateful logic in functional components, which makes them more concise and easier to understand.

The useState hook takes an initial state value as an argument and returns an array with two values: the current state value and a function to update the state. You can then use these values to manage state in your component.

Here’s an example of how you might use useState to manage a counter in a functional component:

				
					import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

				
			

In this example, we first import useState from the React library. We then declare a new state variable called count and a function called setCount to update the state. The initial value of count is set to 0.

We then declare an increment function that updates the count state by calling setCount. Finally, we render the current count value and a button that calls the increment function when clicked.

When the button is clicked, the increment function is called, which updates the count state using setCount. The component then re-renders with the updated state value.

useState is a powerful hook that makes it easy to manage state in functional components. By using it, you can write cleaner and more concise code that is easier to understand and maintain.

Join To Get Our Newsletter
Spread the love