Mastering useEffect in React: A Beginner’s Guide (2025 Edition)
The useEffect hook is one of the most important tools in React. It allows you to perform side effects such as data fetching, DOM manipulation, and more. In this post, we will break down how it works and provide real examples to help you understand it better.
What is useEffect?
useEffect is a built-in hook in React that runs after the component renders. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class-based components.
Basic Syntax
useEffect(() => {
// side effect logic
}, []);
The empty array means the effect runs only once after the initial render.
Common useEffect Use Cases
- Fetching data from an API
- Setting up event listeners
- Cleaning up subscriptions
Example: Fetching Data from API
useEffect(() => {
fetch("https://api.example.com/posts")
.then(response => response.json())
.then(data => setPosts(data));
}, []);
Cleanup Function
Return a function inside useEffect to clean up resources.
useEffect(() => {
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
return () => clearInterval(timer);
}, []);
Mastering useEffect helps you write more efficient and reactive applications.
Comments
Post a Comment