Skip to content
DeveloperMemos

Performing Actions on Page Load with React

React, useEffect, Side Effects1 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 load
6 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:

  • The useEffect hook takes a callback function as its first argument. This function will be executed after the component renders.
  • The empty dependency array [] 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:

  • Fetching data:
    1useEffect(() => {
    2 fetch('https://api.example.com/data')
    3 .then(response => response.json())
    4 .then(data => {
    5 setData(data);
    6 });
    7}, []);
  • Initializing variables or state:
    1useEffect(() => {
    2 const initialValue = 10;
    3 setValue(initialValue);
    4}, []);
  • Setting up event listeners:
    1useEffect(() => {
    2 window.addEventListener('scroll', handleScroll);
    3 return () => {
    4 window.removeEventListener('scroll', handleScroll);
    5 };
    6}, []);

Keep In Mind:

  • Avoid unnecessary re-renders: Using an empty dependency array ensures the effect runs only once. If you need to run the effect based on changes in other values, include those values in the dependency array.
  • Cleanup functions: If you're setting up event listeners or other resources, use the cleanup function returned by useEffect to remove them when the component unmounts.
  • Performance optimization: For performance-critical actions, consider using useLayoutEffect instead of useEffect. However, be cautious as it can lead to performance issues if not used correctly.

More Tips:

  • For more complex logic or data fetching scenarios, consider using libraries like Redux or React Query.
  • Break down large effects into smaller, more focused ones for better code organization and maintainability.

Happy Coding!