Read the full article on Medium and show some support!
1. useState – Managing Component State
The useState
hook lets you add state to functional components. It returns a state variable and a function to update it.
Example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Use Cases:
- Managing form inputs
- Handling UI toggles (like modals, themes, etc.)
- Tracking user interactions
2. useEffect – Handling Side Effects
useEffect
is used to perform side effects like fetching data, updating the DOM, and setting up event listeners.
Example:
import { useState, useEffect } from "react";
function FetchData() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty dependency array means it runs only once (on mount)
return (
<ul>
{data.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
);
}
Use Cases:
- Fetching API data
- Handling event listeners
- Managing subscriptions
3. useContext – Accessing Global State
The useContext
hook allows components to consume values from a React Context without prop drilling.
Example:
import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
function ThemedComponent() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
);
}
Use Cases:
- Managing global themes
- Sharing authentication state
- Avoiding prop drilling
4. useRef – Accessing DOM Elements & Persistent Values
The useRef
hook provides a way to reference a DOM element directly or persist values between renders without causing re-renders.
Example:
import { useRef } from "react";
function FocusInput() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
}
Use Cases:
- Managing uncontrolled form inputs
- Keeping track of previous values
- Storing timers
5. useReducer – Complex State Management
useReducer
is an alternative to useState
for managing complex state logic.
Example:
import { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}
function 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>
);
}
Use Cases:
- Handling complex state logic
- Managing state transitions
- Working with
useContext
for global state
Top comments (0)