React Hooks allow functional components to use state and lifecycle features. Hooks make React applications easier to write and maintain. Below is a table showing common hooks grouped by their type.
| Type | Hook Name | Purpose |
|---|---|---|
| Basic Hooks | useState | Manage component state |
| useEffect | Handle side effects like API calls | |
| useContext | Access global data using Context | |
| DOM / State | useRef | Access DOM elements |
| useReducer | Manage complex state logic | |
| Performance Hooks | useMemo | Optimize performance by memoizing values |
| useCallback | Memoize functions |
1. useState:
The useState hook is used to manage state in functional components.
const [state, setState] = useState(initialValue);import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
<button onClick={() => setCount(count - 1)}>
Decrease
</button>
</div>
);
}
export default Counter;
2. useEffect:
The useEffect hook runs side effects like API calls.
useEffect(() => {
// side effect code
return () => {
// cleanup code (optional)
};
}, [dependencies]);import React, { useEffect } from "react";
function Example() {
useEffect(() => {
console.log("Component mounted");
}, []);
return <h2>Hello World</h2>;
}
export default Example;3. useContext:
The useContext hook allows components to access global data.
1. Create Context:
import React from "react";
const ThemeContext = React.createContext();
export default ThemeContext;2. Provide Context Value:
import React from "react";
import ThemeContext from "./ThemeContext";
import Child from "./Child";
function App() {
return (
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
);
}
export default App;3. Use In Child Component:
import React, { useContext } from "react";
import ThemeContext from "./ThemeContext";
function Child() {
const theme = useContext(ThemeContext);
return <h2>Current Theme: {theme}</h2>;
}
export default Child;