React Hooks have revolutionized how we write functional components, eliminating the need for class components while making state management and side effects more intuitive. In this guide, we'll explore all React Hooks, including the latest ones, with examples to help you integrate them effectively into your projects. 🎯
📌 What Are React Hooks?
React Hooks are built-in functions that allow functional components to use state and lifecycle features without converting them into class components. They make React code cleaner, reusable, and easier to test. 🎉
🏆 Essential React Hooks
1️⃣ useState - Manage Component State 🏗️
The useState
hook allows you to manage local state inside functional components.
import React, { useState } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
2️⃣ useEffect - Handle Side Effects ⚡
The useEffect
hook is used for side effects such as fetching data, subscriptions, or updating the DOM.
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);
}, []);
return <p>Elapsed time: {seconds}s</p>;
};
3️⃣ useContext - Share State Globally 🌍
The useContext
hook provides a way to consume context in functional components without prop drilling.
import React, { createContext, useContext } from "react";
const ThemeContext = createContext("light");
const ThemeSwitcher = () => {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
};
const App = () => (
<ThemeContext.Provider value="dark">
<ThemeSwitcher />
</ThemeContext.Provider>
);
🎯 Advanced React Hooks
4️⃣ useReducer - Manage Complex State 🏗️
The useReducer
hook is an alternative to useState
, useful for managing complex state logic.
import React, { 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;
}
};
const 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>
);
};
5️⃣ useRef - Access DOM Elements 📌
The useRef
hook creates a mutable reference that persists across renders. It's commonly used to access DOM elements directly.
import React, { useRef } from "react";
const FocusInput = () => {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
};
6️⃣ useMemo - Optimize Performance 🚀
The useMemo
hook memoizes a computed value, preventing unnecessary recalculations.
import React, { useState, useMemo } from "react";
const ExpensiveCalculation = ({ num }) => {
const computedValue = useMemo(() => {
return num * 2; // Simulating heavy computation
}, [num]);
return <p>Computed Value: {computedValue}</p>;
};
7️⃣ useCallback - Optimize Functions 📌
The useCallback
hook memoizes functions to prevent unnecessary re-renders.
import React, { useState, useCallback } from "react";
const Button = React.memo(({ handleClick }) => {
console.log("Button re-rendered");
return <button onClick={handleClick}>Click Me</button>;
});
const App = () => {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((prev) => prev + 1);
}, []);
return (
<div>
<p>Count: {count}</p>
<Button handleClick={increment} />
</div>
);
};
🔥 Newest React Hooks (React 18+)
8️⃣ useId - Unique IDs 🆔
useId
generates unique IDs for accessibility attributes.
import { useId } from "react";
const Form = () => {
const id = useId();
return (
<div>
<label htmlFor={id}>Enter Name:</label>
<input id={id} type="text" />
</div>
);
};
🎯 Conclusion
React Hooks provide powerful capabilities to manage state, optimize performance, and handle side effects in functional components. By leveraging hooks like useState
, useEffect
, useMemo
, and useCallback
, you can write more efficient and maintainable React applications! 🚀🔥
Which React Hook do you use the most? Let me know in the comments! 💬
📝 Happy Coding! 🎉
Top comments (0)