đ Exploring React Hooks: A Guide with Examples đ
React hooks are đ functions that let you "hook into" React state and lifecycle features from function components. Since their debut in React 16.8, hooks have revolutionized how we write components, making it easier to manage state, side effects, context, and more!
In this guide, we'll dive into React's most popular hooks with đ¯ examples and explain how they simplify your coding life. Let's get started! đģđ
đ ī¸ 1. useState â Add State to Functional Components đī¸
đ Purpose:
useState đ§° adds state to functional components. It returns an array with two items:
- The current state value.
- A function to update the state.
âī¸ Code Example:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count} đĸ</p>
<button onClick={increment}>â Increment</button>
</div>
);
};
đĄ What's Happening?
The count is our state, and we use setCount to update it when the button is clicked. Super simple! đ
â° 2. useEffect â Handle Side Effects đ
đ Purpose:
useEffect helps you perform side effects like:
- Fetching data đĄ
- Subscribing to events đ
- Updating the DOM manually âī¸
âī¸ Code Example:
import React, { useState, useEffect } from 'react';
const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup âšī¸
}, []); // Empty dependency array means it runs once đ
return <p>Timer: {seconds} âŗ seconds</p>;
};
đĄ What's Happening?
- The timer đ increments every second.
- Cleanup (
clearInterval) ensures no memory leaks! đ§
đ¨ 3. useContext â Simplify Prop Drilling đ
đ Purpose:
useContext đ accesses context values directly, skipping the need for prop drilling.
âī¸ Code Example:
import React, { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
const ThemedComponent = () => {
const theme = useContext(ThemeContext);
return <div>đ¨ The current theme is {theme}.</div>;
};
const App = () => (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
);
đĄ What's Happening?
No more prop passing! đĄī¸ useContext grabs the theme (dark) from the ThemeContext provider.
đ¤ 4. useReducer â Manage Complex State âī¸
đ Purpose:
When state logic gets đ complex, useReducer can replace useState for better clarity.
âī¸ Code Example:
import React, { useReducer } from 'react';
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 };
default: return state;
}
}
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count} đĸ</p>
<button onClick={() => dispatch({ type: 'increment' })}>â Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>â Decrement</button>
</div>
);
};
đĄ What's Happening?
dispatchđ triggers actions (incrementordecrement) to modify state.- Perfect for multi-step or complex updates! đ ī¸
đ¯ 5. useRef â Access DOM Directly đ
đ Purpose:
useRef is like a magical portal đ to interact with DOM elements without causing re-renders.
âī¸ Code Example:
import React, { useRef } from 'react';
const FocusInput = () => {
const inputRef = useRef();
const focusInput = () => {
inputRef.current.focus(); // DOM magic â¨
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>đ Focus Input</button>
</div>
);
};
đĄ What's Happening?
- Clicking the button calls
focusInputto focus the text input. - Handy for forms, animations, or DOM manipulation. đ§ââī¸
đ 6. useMemo â Optimize Expensive Calculations đ
đ Purpose:
useMemo đ§ avoids re-computing expensive calculations unless dependencies change.
âī¸ Code Example:
import React, { useMemo, useState } from 'react';
const ExpensiveCalculation = ({ num }) => {
const result = useMemo(() => {
console.log('Calculating... đ¤');
return num * 2;
}, [num]);
return <p>Result: {result} đĄ</p>;
};
const App = () => {
const [num, setNum] = useState(0);
return (
<div>
<button onClick={() => setNum(num + 1)}>â Increment</button>
<ExpensiveCalculation num={num} />
</div>
);
};
đŦ 7. useCallback â Memoize Functions đ
đ Purpose:
useCallback avoids recreating functions unnecessarily, optimizing component re-renders.
âī¸ Code Example:
import React, { useState, useCallback } from 'react';
const Button = React.memo(({ onClick }) => {
console.log('Button rendered'); // Only re-renders when onClick changes
return <button onClick={onClick}>Click me</button>;
});
const App = () => {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(count + 1), [count]);
return (
<div>
<p>Count: {count} đĸ</p>
<Button onClick={increment} />
</div>
);
};
đĨ 8. useLayoutEffect â Read & React to Layout đŧī¸
đ Purpose:
useLayoutEffect runs synchronously after DOM mutations, before the browser paints.
âī¸ Code Example:
import React, { useLayoutEffect, useState } from 'react';
const LayoutEffectExample = () => {
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
setWidth(window.innerWidth);
}, []);
return <p>Window width: {width} đĨī¸</p>;
};
đ Conclusion
React hooks are a game-changer! From managing state with useState đ to optimizing performance with useMemo âĄ, hooks make React functional components powerful and elegant. Dive into these hooks and elevate your React skills to the next level! đĒâ¨
Happy coding! đģđ
