Call Loading Function with React useEffect



We will use the React useEffect hook to call our loading function. This hook allows us to specify a function that will run on a specific component lifecycle event, such as when the component mounts. By passing in our loading function as a dependency, we ensure that it will be called whenever the component loads or updates.

React useEffect

The useEffect is a Hook in React that allows you to synchronize a component with an external system.

  • It runs after the component renders and can be used to fetch data, update the DOM, or set up event listeners.

  • It takes two arguments: a function that contains the effect logic and a list of dependencies.

  • The effect function should return a cleanup function if necessary.

  • useEffect is similar to componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Approach

You can call a loading function with React's useEffect hook by passing it as a dependency in the hook's second argument. The loading function should be called inside the useEffect's callback function.

Example

import { useEffect } from 'react'; function MyComponent() { useEffect(() => { loadData(); }, []); // Pass an empty array to only call the function once on mount. function loadData() { // Fetch data or perform other loading logic here } // ... component render logic }

You can also pass variables as dependency to the loadData function, so that when the dependency changes, the loadData function will be called again.

import { useEffect } from 'react';

function MyComponent({id}) { useEffect(() => { loadData(id); }, [id]); function loadData(id) { // Fetch data or perform other loading logic here } // ... component render logic }

It is important to note that in order to avoid an infinite loop, any state updates that are caused by the loading function should be done in a separate effect.

Final Code

Here's a working example of using the useEffect hook to load data in a React component ?

App.js

import React, { useEffect, useState } from 'react'; function MyComponent() { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(false); useEffect(() => { async function fetchData() { setIsLoading(true); try { const response = await fetch('https://jsonplaceholder.typicode.com/users'); const json = await response.json(); setData(json); } catch (error) { console.error(error); } finally { setIsLoading(false); } } fetchData(); }, []); if (isLoading) { return <div style={{ color: 'black' }}>Loading...</div>; } if (data) { return <div style={{ color: 'black' }}>{data.map(item => (<div key={item.id}> {item.name} </div>))}</div>; } return <div style={{ color: 'black' }}>No data</div>; } export default MyComponent;

In this example, the MyComponent component uses the useEffect hook to load data from an API when the component is first rendered ?

  • The hook takes two arguments: a callback function that runs when the component is rendered, and an array of dependencies that determine when the effect should be run.

  • In this case, we pass an empty array as the second argument, which tells React to run the effect only once, when the component is first rendered.

  • The callback function fetchData starts by setting the isLoading state to true, which causes the component to display a "Loading?" message.

  • Then it uses the fetch API to load data from an API and await for the response to complete.

  • It then parses the JSON data from the response and sets the data state with the parsed data.

  • If an error occurs, it logs the error to the console. Finally, it sets the isLoading state to false, which causes the component to display the loaded data or a message "No data" if the API returns empty or error.

  • The component renders a different message depending on the current state: "Loading?" while the data is being fetched, the data itself when it's been loaded, and "No data" if the API returns empty or error.

  • Note that this example uses async/await to handle the promise returned by fetch API, if you are using an older version of javascript you can use then() and .catch() methods.

Output

Updated on: 2023-02-16T12:14:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements