Junior — Middle
Can you explain what the useState hook in React is?
sobes.tech AI
Answer from AI
The useState hook in React allows functional components to store and manage state. It returns a pair: the current state value and a function to update it.
Example usage:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state with 0
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
When setCount is called, React updates the state and re-renders the component with the new value.