Introduction
React Hooks allow developers to use state and lifecycle features in functional components. Introduced in React 16.8, hooks simplify component logic and improve code readability. This guide covers the most important React hooks and their use cases.
1. useState – State Management
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
- Manages local component state.
- Accepts an initial state and returns an array with the current state and a function to update it.
2. useEffect – Side Effects
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Elapsed Time: {seconds}s</p>;
}
- Runs side effects like fetching data, subscriptions, or manual DOM manipulation.
- Cleanup function prevents memory leaks.
3. useContext – Context API
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemedComponent() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
- Accesses global state without prop drilling.
- Works well with the Context API.
4. useRef – Referencing DOM Elements
import { useRef, useEffect } from 'react';
function InputFocus() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
- Creates a mutable reference to a DOM element.
- Useful for persisting values across renders without re-rendering.
5. useReducer – Complex State Management
import { useReducer } from 'react';
const reducer = (state, action) => {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
- Alternative to useState for managing complex state logic.
- Uses a reducer function to update state.
6. useMemo – Performance Optimization
import { useMemo, useState } from 'react';
function ExpensiveComputation({ num }) {
const result = useMemo(() => num ** 2, [num]);
return <p>Squared Value: {result}</p>;
}
- Caches expensive calculations to avoid unnecessary recomputations.
- Only re-executes when dependencies change.
7. useCallback – Memoizing Functions
import { useCallback, useState } from 'react';
function Parent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(c => c + 1), []);
return (
<div>
<Child increment={increment} />
<p>Count: {count}</p>
</div>
);
}
- Memoizes functions to prevent unnecessary re-creations.
- Useful in performance optimization.
Conclusion
Understanding and using React hooks effectively can significantly improve your development workflow. These essential hooks cover state management, performance optimizations, and side effects, helping developers build scalable and efficient applications.
Top comments (0)