0

I use useEffect to make an api call only one time after the component is rendered. But it renders two times and I don't understand why. Thank you for your hints.

    useEffect( ()=> {
        // load all pipelines
        console.log("getting all pipelines");
        const api = new Api();
        api
        .get_pipelines()
        .then(response =>{
            getPipelines(response.data.sort((a,b) => (a.pipelineState > b.pipelineState) ? 1 : ((b.pipelineState > a.pipelineState) ? -1 : 0)))
            })
        .catch(error => {
            console.log("error getting existing pipelines", error);
            if(error.response.status === 500 || error.response.status === 404){
                openBanner("Cannot load existing pipelines", "error")
            }
            });
    }, [openBanner]);
mm1975
  • 1,583
  • 4
  • 30
  • 51
  • 1
    Is openBanner updated after the component mounts? That would trigger a rerender – JBrown Apr 01 '23 at 15:12
  • 1
    could be due to react strict mode if u are in dev – cmgchess Apr 01 '23 at 15:12
  • I've tried it also without openBanner and an empty array. Yes I'm in strict mode. How can I change it? – mm1975 Apr 01 '23 at 15:15
  • Can you show the full component? It is also possible that the parent is rendering twice. – JBrown Apr 01 '23 at 15:20
  • 1
    if you are using react 18, you may think about it is this cause your component render 2 times: https://legacy.reactjs.org/docs/strict-mode.html#ensuring-reusable-state – Dolphin Apr 01 '23 at 15:32
  • Yes, I use react 18...Thx all for your hints. Strange behavior! – mm1975 Apr 01 '23 at 15:44
  • 1
    @mm1975 in ur index.js can you try commenting out the – cmgchess Apr 01 '23 at 15:52
  • https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar – cmgchess Apr 01 '23 at 16:19

1 Answers1

1

When you pass an empty dependency array, it indicates to React that the effect does not depend on any props or state changes, so there is no need to re-run the effect when they change. This is useful when you have a side effect that needs to be executed only once when the component mounts, but not on subsequent re-renders.

useEffect(() => {
    /* global google */
    google.accounts.id.renderButton(document.getElementById("signInDiv"), { theme: "outline", size: "large" })
  }, [])

In this specific example, the effect is responsible for rendering a Google sign-in button using the Google Accounts API. By passing an empty dependency array, React ensures that the button is rendered only once when the component mounts, and not on subsequent re-renders.

ash
  • 1,065
  • 1
  • 5
  • 20