✅ How to Use React Hooks (with Tag Examples)
How to Use React Hooks (with Tags)
🧠 useState Hook
Used to store and update state in a functional component.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
⚡ useEffect Hook
Used to handle side effects like fetching data or DOM manipulation.
import { useEffect } from 'react';
function Timer() {
useEffect(() => {
console.log('Component mounted');
}, []);
return Timer started!
;
}
📌 useRef Hook
Used to reference a DOM element or persist values across renders without causing re-render.
import { useRef } from 'react';
function InputFocus() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
);
}
🌐 useContext Hook
Used to consume values from React Context without props drilling.
import { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';
function ThemeButton() {
const theme = useContext(ThemeContext);
return ;
}
🔁 useCallback Hook
Used to memoize a function and prevent unnecessary re-renders.
import { useCallback, useState } from 'react';
function ExpensiveComponent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log('Clicked');
}, []);
return ;
}
📌 Summary of Hooks
useState
: Manage component state
useEffect
: Run side effects (fetch, timer, etc.)
useRef
: Reference DOM or store mutable values
useContext
: Share data across components without props
useCallback
: Optimize performance by memoizing functions
🎯 Master these hooks to write powerful React components!