React JS Tutorial: `useEffect` Lifecycle

beginner
10 min

React JS Tutorial: useEffect Lifecycle

Welcome to our in-depth guide on useEffect in React JS! This tutorial is designed for beginners and intermediate learners, providing a comprehensive understanding of this powerful hook.

šŸŽÆ Introduction to useEffect

useEffect is a built-in hook in React that lets you perform side effects in function components. Side effects include fetching data, manipulating the DOM, and subscribing to events.

šŸ“ Note: In React classes, you'd find these functionalities in the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods. useEffect replaces these methods in function components.

šŸ’” Pro Tip:

When a component renders, React calls the effects. If the component re-renders with the same output, the effects skip execution to optimize performance.

āœ… Setting Up useEffect

useEffect takes two arguments: a function to execute and an optional array of dependencies.

jsx
import React, { useEffect } from 'react'; function MyComponent() { useEffect(() => { // Your code here }, []); // Empty array means the effect runs once (same as componentDidMount) }

šŸ“ Note:

The function in useEffect runs after the component renders for the first time. If you want to run it on mount and update, leave the dependency array empty.

šŸŽÆ Fetching Data with useEffect

Let's build a simple weather app to showcase data fetching with useEffect.

jsx
import React, { useEffect, useState } from 'react'; function WeatherApp() { const [weather, setWeather] = useState(null); useEffect(() => { const fetchData = async () => { const response = await fetch('https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOUR_API_KEY'); const data = await response.json(); setWeather(data); }; fetchData(); }, []); if (!weather) return <p>Loading...</p>; return ( <div> <h1>Weather in London</h1> <p>Temperature: {weather.main.temp}K</p> <p>Description: {weather.weather[0].description}</p> </div> ); }

šŸ“ Note: Replace YOUR_API_KEY with your OpenWeatherMap API key.

šŸŽÆ Cleaning Up with useEffect

If you need to perform cleanup, such as cancelling a subscription or clearing a timer, return a function from your useEffect:

jsx
useEffect(() => { const subscription = SomeAPI.subscribeToUpdates(); return () => { SomeAPI.unsubscribe(subscription); }; }, []);

šŸ’” Pro Tip:

Use a dependency array that includes the variable you want to clean up to ensure cleanup only occurs on unmount.

šŸŽÆ Advanced useEffect Usage

useEffect can accept multiple functions to handle different effects, or skip the dependency array to run effects on every render. For more advanced use cases, explore the official React documentation.

šŸ“ Note:

We encourage you to experiment with the code examples provided and try out different scenarios to build your understanding of useEffect in React JS.

šŸŽÆ Quiz Time!

Quick Quiz
Question 1 of 1

What triggers the function inside `useEffect`?

We hope this tutorial helped you understand the essentials of useEffect in React JS! Happy coding, and remember to keep learning and experimenting. šŸš€šŸŒŸ