Search code examples
reactjsuse-effectreact-lifecycle

Call a function one time on page load


I have 3 useEffect functions each calling a updateData function. (Each one is doing something else in addition to that so I can't combine them all.) Because of this, on page load, updateData gets called 3 times.

Here's the relevant code:

useEffect(() => {
    ...
    updateData();
}, [changePage]);

useEffect(() => {
    ...
    updateData();
}, [search]);

useEffect(() => {
    ...
    updateData();
}, [sortBy]);

How can I make sure that updateData only gets called once on page load?


Solution

  • Add a mount state

    I think this will work. But it feels messy to me. Also maybe state get batched together and you might get some extra triggers from that. So please test it with your setup.

    const [isMountRender, setMountRender] = useState(true);
    
    useEffect(() => {
        ...
        if (isMountRender) return;
        updateData();
    }, [changePage]);
    
    useEffect(() => {
        ...
        if (isMountRender) return;
        updateData();
    }, [search]);
    
    useEffect(() => {
        ...
        if (isMountRender) return;
        updateData();
    }, [sortBy]);
    
    useEffect(() => {
        setMountRender(false)
        updateData();
    }, []);