- What is useState?
useState is a Hook in React, It allows functional components to have state (something only class components could do earlier with this.state).
SYNTAX:
const [state, setState] = useState(initialValue);
state → current value of the state.
setState → function to update the state.
initialValue → the value you want the state to start with.
Alright! Let’s make React Hook super clear, especially from an interview perspective.
1. What is a React Hook?
- Hooks are special functions in React that let you “hook into” React features like state and lifecycle methods in functional components.
- They were introduced in React 16.8 to avoid using class components for stateful logic.
Key idea: Hooks allow functional components to have state, side effects, and more without writing a class.
2. Common React Hooks
- useState → for state management
- useEffect → for side effects like API calls, timers
- useContext → for consuming context
- useReducer → for complex state management
- useRef → to access DOM elements or persist values
3. Why Hooks? (Advantages)
- No need for class components → simpler, cleaner code.
- Reuse stateful logic across components (custom hooks).
- Better separation of concerns in components.
- Avoids confusion with
this
keyword in classes.
4. Where to use Hooks?
- Only inside functional components or custom hooks.
- Not in loops, conditions, or nested functions → must be top-level.
5. How to use a Hook?
Example with useState
:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Hook usage
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Top comments (0)