Introduction to React Hooks
3 min | March 10, 2025
React Hooks are a powerful feature introduced in React 16.8 that allows developers to manage state and lifecycle methods inside functional components. Hooks eliminate the need for class components while making React code more readable and maintainable.
In this guide, we'll explore two essential hooks: useState for state management and useEffect for handling side effects.
What are React Hooks?
React Hooks are functions that let you "hook into" React features such as state and lifecycle methods from functional components. Some of the most commonly used hooks include:
- useState – Manages local component state.
- useEffect – Handles side effects like data fetching.
- useContext – Accesses context data without prop drilling.
- useReducer – Manages complex state logic.
- useRef – Maintains references to DOM elements and values without causing re-renders.
Using useState for State Management
The useState hook allows functional components to manage local state. It returns a state variable and a function to update it.
Example: Counter Component
javascript1import { useState } from "react"; 2 3const Counter = () => { 4 const [count, setCount] = useState(0); 5 6 return ( 7 <div> 8 <h2>Counter</h2> 9 <p>Count: {count}</p> 10 <button onClick={() => setCount(count + 1)}>Increment</button> 11 <button onClick={() => setCount(count - 1)}>Decrement</button> 12 </div> 13 ); 14}; 15 16export default Counter;
Explanation:
- useState(0) initializes count to 0.
- setCount updates the state when the buttons are clicked.
Using useEffect for Side Effects
The useEffect hook allows you to perform side effects in function components, such as data fetching, subscriptions, or manually changing the DOM.
Example: Fetching Data
javascript1import { useEffect, useState } from "react"; 2 3const DataFetcher = () => { 4 const [data, setData] = useState(null); 5 6 useEffect(() => { 7 fetch("https://jsonplaceholder.typicode.com/posts/1") 8 .then((response) => response.json()) 9 .then((json) => setData(json)); 10 }, []); // Empty dependency array ensures it runs once when the component mounts 11 12 return ( 13 <div> 14 <h2>Data Fetcher</h2> 15 {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : "Loading..."} 16 </div> 17 ); 18}; 19 20export default DataFetcher;
Explanation:
- The useEffect hook runs once when the component mounts because of the empty dependency array [].
- It fetches data from an API and updates the state with the response.
- The component displays the fetched data or a loading message.
Conclusion
React Hooks simplify state management and lifecycle methods in functional components, making them more efficient and readable. In this post, we covered useState and useEffect, but there are many more hooks to explore, such as useContext, useReducer, and useRef.
By mastering hooks, you can build powerful and maintainable React applications with ease!