useState
HookThe useState
hook allows you to add state management in functional components. It lets you define a state variable and a function to update it.
useState
π Example: Counter Component
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
πΉ Explanation:
useState(0)
initializes the state count
to 0
.setCount
is the function that updates the state.useEffect
HookThe useEffect
hook is used for side effects in React components, like fetching data, updating the DOM, or subscribing to external events.
useEffect
π Example: Fetching Data with useEffect
import React, { useState, useEffect } from "react";
function FetchData() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, []); // Empty array means the effect runs only once when the component mounts
return loading ? <p>Loading...</p> : <ul>{data.map((item) => <li key={item.id}>{item.name}</li>)}</ul>;
}
export default FetchData;
πΉ Explanation:
useEffect
runs once when the component mounts due to the empty dependency array []
.data
state variable, while showing a loading message until data is fetched.useContext
HookThe useContext
hook allows you to consume context directly in functional components. It is a simpler way to access the context values compared to the Context.Consumer
in class components.
π Example: Creating a Context (ThemeContext.js
)
import React, { createContext, useState } from "react";
export const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme(theme === "light" ? "dark" : "light");
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
π Example: Using useContext
in a Component
import React, { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
function ThemeSwitcher() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
}
export default ThemeSwitcher;
Step 3: Wrap the App with the Provider
import React from "react";
import { ThemeProvider } from "./ThemeContext";
import ThemeSwitcher from "./ThemeSwitcher";
function App() {
return (
<ThemeProvider>
<ThemeSwitcher />
</ThemeProvider>
);
}
export default App;
πΉ Explanation:
ThemeContext
is created to manage theme state.useContext(ThemeContext)
allows us to access the theme
and toggleTheme
directly in the ThemeSwitcher
component.useReducer
HookThe useReducer
hook is an alternative to useState
for managing complex state logic. It’s often used when the state depends on multiple sub-values or when the next state value depends on the previous one.
useReducer
π Example: Counter with useReducer
import React, { useReducer } from "react";
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;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>Increment</button>
<button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>
</div>
);
}
export default Counter;
πΉ Explanation:
useReducer
is used for managing state with more complex logic.reducer
function that handles the state transitions.dispatch
is used to trigger actions that update the state.useRef
HookThe useRef
hook allows you to access and persist values across renders without causing re-renders.
useRef
π Example: Referencing a DOM Element
import React, { useRef } from "react";
function FocusInput() {
const inputRef = useRef();
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default FocusInput;
useState
, useEffect
, useContext
, useReducer
, and useRef
are among the most commonly used hooks.By mastering React hooks, you can build scalable and efficient React applications! π