HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React useState Hook

React useState

The 'useState' hook is a fundamental React hook that allows functional components to manage state.

It takes an initial state value as an argument and returns an array with two elements: the current state value and a function that allows you to update the state.

Here's a basic example of how to use the 'useState' hook:

import React, { useState } from 'react';
function Counter() {
// Declare a state variable named 'count' with an initial value of 0
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
{/* Call setCount to update the 'count' state */}
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}

export default Counter;

In the example above:

  • 'count' is the state variable that holds the current value.
  • 'setCount' is the function that you use to update the state. When you call 'setCount(newValue)', React will re-render the component with the updated state value.