Blog>
Snippets

Implementing Prefetching for Smooth User Experience

Illustrate prefetching data for a component that isn't yet mounted but will be soon, ensuring the data is ready by the time the user navigates to it.
import { useEffect } from 'react';
import axios from 'axios';
This piece of code imports the useEffect hook from React for running side-effects, and axios for making HTTP requests.
const fetchData = async () => {
  try {
    const response = await axios.get('https://api.example.com/data');
    return response.data;
  } catch (error) {
    console.error('Error fetching data:', error);
    return null;
  }
};
Defines an asynchronous function fetchData which uses axios to fetch data from a given API endpoint and returns the data on success or logs an error and returns null on failure.
useEffect(() => {
  const data = fetchData();
  data.then(fetchedData => {
    if (fetchedData) {
      console.log('Data pre-fetched successfully:', fetchedData);
    }
  });
}, []);
This useEffect hook calls the fetchData function to pre-fetch data as soon as the component mounts. The empty dependency array [] ensures this effect only runs once when the component mounts.