What is useState?
In React, state refers to data that can change over time and affect how a component behaves or looks. The useState hook provides a way to introduce state variables into functional components. Before hooks were introduced, state management was only possible in class components, but with the advent of hooks, functional components can now hold and manage state as well.
const [state, setState] = useState(initialValue);
- state: The current state value.
- setState: The function to update the state.
- initialValue: The initial value of the state when the component first renders.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Conclusion
The useState hook is a versatile and powerful tool for managing state in React functional components. Whether you’re handling simple variables or more complex data structures, useState provides a straightforward and effective way to make your components dynamic and interactive.