Loading

Quipoin Menu

Learn • Practice • Grow

react / useState Hook in React
interview

Q1. What is the useState hook?
useState is a React hook that lets you add state to functional components. It returns an array with two elements: the current state value and a function to update it. The hook takes an initial state as an argument. Example: const [count, setCount] = useState(0).

Q2. How do you update state with useState?
You call the setter function returned by useState with the new value. Example: setCount(5). If the new value depends on the previous state, you can pass a function: setCount(prevCount => prevCount + 1). This ensures you work with the latest state.

Q3. Can you use multiple useState hooks in one component?
Yes, you can call useState multiple times to manage different state variables. For example: const [name, setName] = useState(''); const [age, setAge] = useState(0). React identifies each hook by its order of calls, so you must not call hooks conditionally.

Q4. What happens when you call the setter function?
Calling the setter function schedules an update to the component. React will re-render the component with the new state value. The setter is asynchronous, so if you read state immediately after setting, you may get the old value. Use the functional update to avoid stale closures.

Q5. How do you use useState with objects?
When state is an object, you must merge changes manually because the setter replaces the entire state. Example: setUser({ ...user, name: 'NewName' }). Unlike class components, useState does not automatically merge objects.