Is there a way to do an api call only once in react functional component?

Asked
Active3 hr before
Viewed126 times

9 Answers

componentreact
90%

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works., Did all European countries choose to evacuate their diplomats from Afghanistan? ,thew problem I face is that everytime I use setList, the component is redraw, so the http call is reexecute.

const ItemRelationsList = (props: ItemRelationsListProps): JSX.Element => {
    const [getList, setList] = useState([]);

    // componentDidMount
    useEffect(() => {
        loadRelation()
    }, [])

    const loadRelation = (): void => {
        HttpService.GetAsync<getListRequest, getListResponse>('getList',{
            // params
        }).subscribe(res => {
            setList(res.data.list);
        });
    }

    return (
        <>
            <Table
                columns={columns}
                dataSource={getList}
            >
            </Table>
        </>
    )
}
88%

Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.,The Effect Hook, useEffect adds the ability to perform side effects from a function component.,Here is what a typical React code looks like for both ordinary class component and functional component using Hooks.

You can also decide when to re-render. Consider below the example where we have passed a count array after the useEffect.

useEffect(() => {
   document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
72%

Pretag
 Pretag team - issue, fix, solve, resolve
65%

That will ensure the useEffect only runs once. ,React has a built-in hook called useEffect. Hooks are used in function components. The Class component comparison to useEffect are the methods componentDidMount, componentDidUpdate, and componentWillUnmount.,useEffect will run when the component renders, which might be more times than you think. I feel like I’ve had this come up a dozen times in the past few weeks, so it seems worthy of a quick blog post.

import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Run! Like go get some data from an API.
  });

  return (
    <div>
      {/* Do something with data. */}
    </div>
  );
}

Or, put nothing:

import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Run! Like go get some data from an API.
  }, []);

  return (
    <div>
      {/* Do something with data. */}
    </div>
  );
}
load more v
75%

If you run this code, you can see that the useEffect hook will be called only after executing all the code inside our component. The class equivalent code of this snippet would be something like this:,In this code, the code inside useEffect will only get executed once even if we change the value of the variable count multiple times. It'd print "Hello from the component!" twice but it'd print "Hello from useEffect" only once.,Have you ever faced this issue that your useEffect hook gets executed multiple times? Maybe sometimes it goes into the infinite loop?

import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    console.log('Hello from useEffect!');
  });
  console.log('Hello from the component!');

  return (
    <div>Hello World</div>
  );
}

export default App;
load more v
40%

The Effect Hook lets you perform side effects in function components:,We’ve learned that useEffect lets us express different kinds of side effects after a component renders. Some effects might require cleanup so they return a function:,There are two common kinds of side effects in React components: those that don’t require cleanup, and those that do. Let’s look at this distinction in more detail.

import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v
22%

The only goal of this function is to access the data and to convert the response into JSON using the data.json() method. GET is the default action, so you don’t need any other parameters.,You will be using React components and Hooks in this tutorial, including the useState and useEffect Hooks. You can learn about components and Hooks in our tutorials How To Manage State with Hooks on React Components and How To Handle Async Data Loading, Lazy Loading, and Code Splitting with React.,You’ll use this file for any actions on the /list endpoint. Add a function to retrieve the data using the fetch function:

Pretag
 Pretag team - issue, fix, solve, resolve
60%

How React components fetch data,How to fetch data in React,How to fetch data in higher-order components

Pretag
 Pretag team - issue, fix, solve, resolve
48%

The relationship between class and functional components made sense until the moment functional components needed to do things that only class components could do (i.e hold state, respond to lifecycle changes).,Earlier on in React, components were either class components or functional components. Functional components were Javascript functions that accepted props (data) to display and returned JSX.,Consequently, functional components would be converted to class components or class components were created as wrappers for functional components. This was inconvenient and all changed with React version 16.8.

First, remove all the JSX code in the <header> inside of the file src/App.js and replace it with the following HTML.

....
<h1>
   Fetching Data with React Hooks
</h1>
....

Add a state variable using the React hook useState at the top of the function.

....
function App() {
let [responseData, setResponseData] = React.useState(''); // new

return (
<div className="App">
   ....

The next step is to add useEffect to the file and give the variable responseData a value when the component loads.

....
function App() {
  let [responseData, setResponseData] = React.useState('');

  React.useEffect(() => {
    setResponseData('hello')
    console.log(responseData)
  }, [setResponseData, responseData])

  return (
    <div className="App">
....

Next, replace the code inside of React.useEffect() with,

....
axios({
      "method": "GET",
      "url": "https://quotes15.p.rapidapi.com/quotes/random/",
      "headers": {
         "content-type": "application/octet-stream",
         "x-rapidapi-host": "quotes15.p.rapidapi.com",
         "x-rapidapi-key": process.env.REACT_APP_API_KEY
      },
      "params": {
         "language_code": "en"
      }
   })
   .then((response) => {
      setResponseData(response.data)
   })
   .catch((error) => {
      console.log(error)
   })
   ....

Finally, below the <header> JSX tag, add this code so we can see the response data that is being fetched,

....
      <pre>
        <code>
          {responseData && JSON.stringify(responseData, null, 4)}
        </code>
      </pre>
....
load more v

Other "component-react" queries related to "Is there a way to do an api call only once in react functional component?"