Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
React Hooks revolutionized how we write components by
bringing state and side effects to functional components. This chapter
will help you master hooks from foundational to advanced use cases and even
build your own custom hooks.
🧠 Why This Chapter
Matters
Hooks let you write cleaner, more reusable, and testable
components using functions instead of classes. They simplify logic and
eliminate the need for lifecycle methods like componentDidMount.
In this chapter, you’ll learn:
✅ 1. What Is a Hook?
Hooks are special functions that let you "hook
into" React's features — like state, context, or lifecycle — without
using classes.
🧩 Rules of Hooks:
✅ 2. useState — Add State to
Functional Components
import
{ useState } from 'react';
function
Counter() {
const [count, setCount] = useState(0);
return (
<>
<h2>{count}</h2>
<button onClick={() => setCount(count
+ 1)}>+</button>
</>
);
}
Term |
Meaning |
useState(0) |
Initializes state with value 0 |
count |
Current state value |
setCount |
Function to update state |
✅ 3. useEffect — Handle Side
Effects
Used for:
useEffect(()
=> {
document.title = `Count: ${count}`;
},
[count]); // runs when `count` changes
Cleanup with return:
useEffect(()
=> {
const timer = setInterval(() => console.log('Tick'),
1000);
return () => clearInterval(timer); //
cleanup
},
[]);
✅ 4. useContext — Avoid Prop
Drilling
const
ThemeContext = React.createContext();
function
App() {
return (
<ThemeContext.Provider
value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function
Toolbar() {
const theme = useContext(ThemeContext);
return <h1>Theme: {theme}</h1>;
}
✅ useContext() gives you access
to context values deep in the component tree.
✅ 5. useRef — Persistent Values
& DOM Access
const
inputRef = useRef();
function
FocusInput() {
return (
<>
<input ref={inputRef} />
<button onClick={() =>
inputRef.current.focus()}>Focus</button>
</>
);
}
Also useful for storing values that don’t trigger
re-renders, like a previous state.
const
prevCount = useRef();
useEffect(()
=> {
prevCount.current = count;
},
[count]);
✅ 6. useReducer — Advanced State
Management
jsx
CopyEdit
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
[state, dispatch] = useReducer(reducer, initialState);
✅ Great for complex state logic,
especially forms or nested updates.
✅ 7. useCallback — Memoize
Functions
const
memoizedClick = useCallback(() => {
console.log('Clicked');
},
[]);
✅ Prevents function recreation on
every render — useful when passing functions to child components.
✅ 8. useMemo — Memoize Expensive
Computations
const
expensiveValue = useMemo(() => computeHeavyStuff(data), [data]);
✅ Only recalculates when data
changes.
✅ 9. Custom Hooks — Reuse Hook
Logic
Custom hooks are just functions that start with use
and contain other hooks.
function
useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) :
initialValue;
});
useEffect(() => {
localStorage.setItem(key,
JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
✅ Clean, reusable, and testable
logic across components.
🧪 Example: useForm Custom
Hook
function
useForm(initial = {}) {
const [form, setForm] = useState(initial);
const handleChange = (e) => {
setForm({ ...form, [e.target.name]:
e.target.value });
};
return [form, handleChange];
}
//
Usage
const
[data, handleInput] = useForm({ name: '', email: '' });
✅ Summary Table
Hook |
Purpose |
Best Use Case |
useState |
Adds state to function components |
Counter, toggles, inputs |
useEffect |
Runs after render (side effects) |
API calls, timers, DOM updates |
useContext |
Reads values from context |
Global state, theming, auth |
useRef |
Persistent value without re-render |
Accessing DOM, storing previous values |
useReducer |
Complex state management |
Form, shopping cart, game logic |
useCallback |
Memoize functions to avoid re-renders |
Stable event handlers |
useMemo |
Memoize expensive calculations |
Sorting, filtering, derived values |
Custom Hook |
Reusable logic built from hooks |
Forms, fetchers, animations |
React is a JavaScript library for building user interfaces. It’s fast, modular, and backed by Facebook, making it popular for modern frontend development.
Yes. A solid understanding of ES6+ JavaScript (like arrow functions, destructuring, and promises) is essential.
A component is a UI building block; a hook is a function that lets you “hook into” React features inside functional components.
Technically a library, but it’s often considered a framework because it’s used to build entire applications.
useState, useEffect, useContext, useRef, and useMemo are most commonly used.
Yes — but Node.js is typically used for tooling, package management, and running development servers.
✅ Yes — for large, complex apps. But for small to medium apps, Context API and hooks are often enough.
Basic concepts can be learned in a few weeks; becoming proficient depends on how often you build projects and practice.
It depends on your project needs, but React is widely adopted and has a huge community, making it a strong choice.
You
can deploy to services like Vercel, Netlify, or GitHub Pages with just a
few clicks — or use traditional hosting for more control.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)