
What Are Hooks?
React Hooks were introduced in React 16.8 to enable functional components to manage state and lifecycle features without needing class components. Hooks simplify code, making it more readable and reusable.
Before Hooks, functional components were stateless and could not handle lifecycle methods. Developers relied on class components to manage local states and side effects. Hooks revolutionized this by allowing state and other React features within functional components.
useState – Managing State in Functional Components
The useState
Hook allows you to add state to a functional component. It returns an array with two elements:
- The current state.
- A function to update the state.
Syntax:
const [state, setState] = useState(initialValue);
Example:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
In this example, useState(0)
initializes count
to 0
. Clicking the button updates the state using setCount
.
useEffect – Handling Side Effects
The useEffect
Hook allows you to perform side effects in functional components. Side effects include fetching data, updating the DOM, and subscribing to external sources.
Syntax:
useEffect(() => { // Side effect logic return () => { // Cleanup logic (optional) }; }, [dependencies]);
Example:
import React, { useState, useEffect } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds(prevSeconds => prevSeconds + 1); }, 1000); return () => clearInterval(interval); // Cleanup function }, []); return <p>Timer: {seconds} seconds</p>; } export default Timer;
Here, useEffect
runs once when the component mounts, starting an interval. The cleanup function prevents memory leaks by clearing the interval when the component unmounts.
useContext – Global State Management
The useContext
Hook provides a way to manage global state without prop drilling. It enables data sharing between components without manually passing props down the component tree.
Creating and Using Context:
import React, { useState, useContext, createContext } from 'react'; const ThemeContext = createContext(); function ThemeProvider({ children }) { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={{ theme, setTheme }}> {children} </ThemeContext.Provider> ); } function ThemedComponent() { const { theme, setTheme } = useContext(ThemeContext); return ( <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff', padding: '20px' }}> <p>Current Theme: {theme}</p> <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle Theme</button> </div> ); } function App() { return ( <ThemeProvider> <ThemedComponent /> </ThemeProvider> ); } export default App;
In this example, ThemeContext
manages the theme state globally. ThemedComponent
consumes the context without prop drilling.
Conclusion
React Hooks simplify state management and side effects in functional components. The core Hooks—useState
, useEffect
, and useContext
—empower developers to build more efficient, readable, and maintainable React applications. Understanding these Hooks is essential for modern React development.
Stay tuned for more advanced Hooks like useReducer
, useRef
, and useMemo
!
Leave a Comment