π Introduction
When I first started learning React, I kept hearing about something called "Hooks" β and how they changed the way we write components forever.
So what exactly are React Hooks?
And why do we even need them?
Letβs break it down in simple terms β with real-world examples.
π§ What Are Hooks?
Hooks are special functions that let you "hook into" React features like:
State (useState)
Lifecycle (useEffect)
Context (useContext)
Refs (useRef)
Memoization (useMemo, useCallback)
They work only in functional components and eliminate the need for class-based components in most cases.
β
Why Hooks?
Before hooks, we needed class components to manage state and lifecycle methods. Now, thanks to hooks, you can write everything using simple functional components.
Benefits:
Less boilerplate
Easier to read and reuse
No this keyword mess
π Commonly Used Hooks
1οΈβ£ useState β Add State to Functional Components
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
2οΈβ£ useEffect β Run Side Effects (like API calls, timers, etc.)
import { useEffect, useState } from 'react';
function Posts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(data => setPosts(data));
}, []); // Run once on mount
return (
<ul>
{posts.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
);
}
3οΈβ£ useRef β Refer to DOM elements or persist values
import { useRef } from 'react';
function InputFocus() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} placeholder="Click the button to focus" />
<button onClick={handleFocus}>Focus Input</button>
</>
);
}
4οΈβ£ useContext β Consume Global Context Without Props
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button className={`bg-${theme}-500 text-white`}>Theme Button</button>
);
}
5οΈβ£ useMemo β Optimize Performance for Expensive Calculations
import { useMemo, useState } from 'react';
function ExpensiveCalculation({ number }) {
const [multiplier, setMultiplier] = useState(2);
const result = useMemo(() => {
console.log('Calculating...');
return number * multiplier;
}, [number, multiplier]);
return <p>Result: {result}</p>;
}
6οΈβ£ useCallback β Memoize Functions
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
β Useful when passing functions to child components (prevents re-renders)
π Bonus: Custom Hooks
You can create your own hooks to reuse logic:
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
π Rules of Hooks
β
Always use hooks at the top level (no conditions/loops)
β Only call hooks inside React functions (not regular JS functions)
π§ When to Use Which Hook?
Goal Hook
Add local state useState
Run side effects (fetch) useEffect
Access DOM elements useRef
Use global context useContext
Optimize performance useMemo
Memoize event handlers useCallback
Share logic across components Custom Hooks
π§βπ» Final Thoughts
Hooks made React cleaner, simpler, and more powerful.
Theyβre now the standard way to build modern React apps β and once you get comfortable with them, youβll wonder how you ever wrote React without them.
π¬ Whatβs Next?
Want to learn real-world use cases for each hook?
Follow me β Iβll be posting deep dives into each React Hook with project examples, performance tips, and best practices.
Top comments (0)