React JS: Automatically Call a Function on Page Load (2026)

Discover how to automatically trigger functions in React JS when a page loads. Perfect for fetching data from a server with useEffect.

React JS: Automatically Call a Function on Page Load (2026)

React JS: Automatically Call a Function on Page Load (2026)

React JS is a powerful library for building user interfaces, but developers often encounter challenges when they need to perform certain actions automatically when a page loads. One common task is fetching data from a server as soon as a component mounts. In this tutorial, we will explore how to automatically call a function, such as fetching notes from a MongoDB server, when a React component loads.

Key Takeaways

  • Use the useEffect hook to execute functions on component mount.
  • Fetch data from a server using fetch or axios inside useEffect.
  • Manage state with useState to store and display fetched data.
  • Understand how dependencies affect useEffect execution.

Introduction

Knowing how to trigger functions automatically on page load can greatly enhance your React applications, especially for tasks like data fetching. This tutorial will demonstrate how to use the useEffect hook to achieve this in a React component. We will walk through setting up a simple note-taking application that fetches and displays notes from a MongoDB server.

Prerequisites

  • Basic understanding of React and functional components
  • Node.js and npm installed on your system
  • A React project set up using Create React App

Step 1: Setting Up Your React Environment

First, ensure you have a React project ready. If not, you can create one using Create React App:

npx create-react-app note-app

Navigate into your project directory:

cd note-app

Step 2: Installing Axios for HTTP Requests

We'll use Axios to handle HTTP requests. Install it using npm:

npm install axios

Step 3: Creating the Notes Component

Create a new component, Notes.js, to fetch and display notes:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const Notes = () => {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    const fetchNotes = async () => {
      try {
        const response = await axios.get('http://localhost:5000/api/notes');
        setNotes(response.data);
      } catch (error) {
        console.error('Error fetching notes:', error);
      }
    };

    fetchNotes();
  }, []); // Dependency array ensures this runs only once on mount

  return (
    
      Notes
      
        {notes.map(note => (
          {note.title}: {note.content}
        ))}
      
    
  );
};

export default Notes;

Step 4: Understanding useEffect and Dependency Arrays

The useEffect hook is essential for side effects in functional components. It takes two arguments: a function and a dependency array. The function runs after the component mounts, and whenever dependencies change. An empty array runs the effect only once.

Step 5: Adding the Notes Component to Your App

Integrate the Notes component into your main App.js:

import React from 'react';
import Notes from './Notes';

function App() {
  return (
    
      
        Note Taking App
        
      
    
  );
}

export default App;

Common Errors/Troubleshooting

  • Network Errors: Ensure your MongoDB server is running and accessible.
  • Dependency Array Mistakes: Adding state variables unnecessarily can lead to infinite loops.

Conclusion

By using the useEffect hook, you can easily perform actions like fetching data when a component loads. This method helps keep your code clean and efficient, especially when combined with hooks like useState for managing component state.

Frequently Asked Questions

Why use useEffect for data fetching?

useEffect is designed for side effects in React components, such as data fetching, and ensures code runs after the component mounts.

Can I use fetch instead of Axios?

Yes, fetch is a native browser API for HTTP requests and can be used in place of Axios, though Axios offers more features out of the box.

What is the purpose of the dependency array?

The dependency array controls when the effect should re-run. An empty array means the effect runs only once after the component mounts.