Hooks (useState, useEffect, useContext, useReducer)
Master functional component state management, side-effects, context providers, state reduction, and custom hook hooks.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What are React Hooks and why were they introduced?
// Hooks allow functional components to have state and lifecycle
// Before Hooks: only class components could have state/lifecycle
// After Hooks: functional components became powerful
// useState - add state to functional components
const [count, setCount] = useState(0);
// useEffect - handle side effects
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
// useContext - access context
const theme = useContext(ThemeContext);
// useReducer - complex state management
const [state, dispatch] = useReducer(reducer, initialState);
Q2. How do you create custom hooks?
// Custom hook - reusable logic
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
// Using custom hook
function Component() {
const width = useWindowWidth();
return <p>Width: {width}</p>;
}
// Custom hook for API calls
function useApi(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
Q3. What is useReducer and when should you use it?
// useReducer for complex state logic
const initialState = { count: 0 };
function reducer(state, action) {
switch(action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
case 'RESET':
return { count: 0 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
<button onClick={() => dispatch({ type: 'RESET' })}>Reset</button>
</div>
);
}
Q4. What are the rules of Hooks?
// Rules of Hooks (must follow)
// 1. Only call hooks at the top level
// DON'T - call inside conditions
function BadComponent({ condition }) {
if (condition) {
const [state, setState] = useState(0); // WRONG!
}
}
// DO - call at top level
function GoodComponent({ condition }) {
const [state, setState] = useState(0); // CORRECT
}
// 2. Only call hooks from React functions
// DON'T - call from regular JavaScript functions
function myFunction() {
useState(0); // WRONG!
}
// DO - call from components or custom hooks
function MyComponent() {
useState(0); // CORRECT
}
// 3. Use ESLint plugin
import { useEffect, useState } from 'react';
// Dependency array is critical
useEffect(() => {
console.log('Effect');
}, [dependency]); // Don't forget dependency array!
Q5. How do you handle side effects with useEffect?
// Basic useEffect
function Component() {
useEffect(() => {
console.log('Component mounted or updated');
});
}
// Run only on mount
function Component() {
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(data => setData(data));
}, []); // Empty dependency array
}
// Run when dependency changes
function Component({ id }) {
useEffect(() => {
fetch(`/api/user/${id}`)
.then(res => res.json())
.then(data => setUser(data));
}, [id]); // Run when id changes
}
// Cleanup function
function Component() {
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer');
}, 1000);
// Cleanup
return () => clearInterval(timer);
}, []);
}
Q6. What is useContext and how does it solve prop drilling?
// Create context
const ThemeContext = React.createContext();
// Provider
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Header />
<Main />
</ThemeContext.Provider>
);
}
// Consumer
function DeepComponent() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === 'light' ? 'white' : 'black' }}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
}
// Multiple contexts
const UserContext = React.createContext();
const NotificationContext = React.createContext();
Q7. What is useMemo and when should you use it?
const value = useMemo(() => expensiveCalculation(data), [data]);useMemo caches expensive computed values and recomputes them only when dependencies change.
Q8. What is useCallback and why is it useful?
const fn = useCallback(() => doSomething(id), [id]);useCallback memoizes function references to reduce unnecessary child re-renders.
Q9. What is useRef and what are its common use cases?
const inputRef = useRef(null); inputRef.current.focus();useRef stores mutable values and accesses DOM elements without causing re-renders.
Q10. What is the difference between useMemo and useCallback?
| Hook | Purpose |
|---|---|
| useMemo | Memoizes a computed value |
| useCallback | Memoizes a function |
Hooks (useState, useEffect, useContext, useReducer)
Master functional component state management, side-effects, context providers, state reduction, and custom hook hooks.
What are React Hooks and why were they introduced?
// Hooks allow functional components to have state and lifecycle // Before Hooks: only class components could...
How do you create custom hooks?
// Custom hook - reusable logic function useWindowWidth() { const [width, setWidth] = useState(window.innerW...
What is useReducer and when should you use it?
// useReducer for complex state logic const initialState = { count: 0 }; function reducer(state, action) {...
What are the rules of Hooks?
// Rules of Hooks (must follow) // 1. Only call hooks at the top level // DON'T - call inside conditions func...
How do you handle side effects with useEffect?
// Basic useEffect function Component() { useEffect(() => { console.log('Component mounted or updated');...
What is useContext and how does it solve prop drilling?
// Create context const ThemeContext = React.createContext(); // Provider function App() { const [theme, se...
What is useMemo and when should you use it?
const value = useMemo(() => expensiveCalculation(data), [data]);useMemo caches expensive computed values and r...
What is useCallback and why is it useful?
const fn = useCallback(() => doSomething(id), [id]);useCallback memoizes function references to reduce unneces...
What is useRef and what are its common use cases?
const inputRef = useRef(null); inputRef.current.focus();useRef stores mutable values and accesses DOM elements...
What is the difference between useMemo and useCallback?
HookPurposeuseMemoMemoizes a computed valueuseCallbackMemoizes a function