useEffect LifecycleWelcome 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.
useEffectuseEffect 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.
When a component renders, React calls the effects. If the component re-renders with the same output, the effects skip execution to optimize performance.
useEffectuseEffect takes two arguments: a function to execute and an optional array of dependencies.
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Your code here
}, []); // Empty array means the effect runs once (same as componentDidMount)
}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.
useEffectLet's build a simple weather app to showcase data fetching with useEffect.
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.
useEffectIf you need to perform cleanup, such as cancelling a subscription or clearing a timer, return a function from your useEffect:
useEffect(() => {
const subscription = SomeAPI.subscribeToUpdates();
return () => {
SomeAPI.unsubscribe(subscription);
};
}, []);Use a dependency array that includes the variable you want to clean up to ensure cleanup only occurs on unmount.
useEffect UsageuseEffect 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.
We encourage you to experiment with the code examples provided and try out different scenarios to build your understanding of useEffect in React JS.
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. šš