1

I have the following code snippet in use while wrapping my whole React application with <React.StrictMode>.

function Quiz() {

    const fetchData = useCallback(
        async () => {
            console.log("hiho");
        },
        []
    );

    useEffect(() => {
        fetchData();
    }, [fetchData])

    return (
        <>
        </>
    )
}

For the initial load of my application fetchData is being called twice within my useEffect(). I am a bit puzzled as I assumed that useCallback() would prevent this (even though StrictMode calls the rendering twice).

Should I be worried that fetchData get's called twice? In my case fetchData returns random data which then has the side effect that the data changes during the render process on dev.

Edyta
  • 11
  • 2
  • I think the answer to your question is here: https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar – ltanica Jun 03 '22 at 21:50

1 Answers1

-1

Try removing the fetchData from the useEffect dependency array. I believe that should render it just once.

function Quiz() {
    const fetchData = useCallback(
        async () => {
            console.log("hiho");
        },
        []
    );

    useEffect(() => {
        fetchData();
    }, [])

    return (
        <>
        </>
    )
}
Bhupen
  • 1,270
  • 1
  • 12
  • 27