— React, useEffect, Side Effects — 1 min read
In React, the useEffect
hook is the primary tool for performing side effects, including actions that need to happen when a component mounts or updates. To execute code on page load, we can utilize this hook with an empty dependency array.
Basic Example:
1import React, { useEffect } from 'react';2
3function MyComponent() {4 useEffect(() => {5 // Code to be executed on page load6 console.log('Component mounted!');7 // Fetch data, initialize variables, etc.8 }, []);9
10 return (11 <div>12 {/* Component content */}13 </div>14 );15}16
17export default MyComponent;
Explanation:
useEffect
hook takes a callback function as its first argument. This function will be executed after the component renders.[]
as the second argument tells React to run the effect only once when the component mounts, effectively making it equivalent to a page load event.Common Use Cases:
1useEffect(() => {2 fetch('https://api.example.com/data')3 .then(response => response.json())4 .then(data => {5 setData(data);6 });7}, []);
1useEffect(() => {2 const initialValue = 10;3 setValue(initialValue);4}, []);
1useEffect(() => {2 window.addEventListener('scroll', handleScroll);3 return () => {4 window.removeEventListener('scroll', handleScroll);5 };6}, []);
Keep In Mind:
useEffect
to remove them when the component unmounts.useLayoutEffect
instead of useEffect
. However, be cautious as it can lead to performance issues if not used correctly.More Tips:
Happy Coding!