7

I know why this happens but want to know what´s the right approach to avoid it. useEffect is called twice. one with data = null and then with "real" data.

const [data, setData] = useState(null);
someServiceToFetchData.then(freshData => setData(freshData))

useEffect(() => {
    console.log("useEffect called");
}, [data]);

should I do something like this everywhere?

useEffect(() => {
    if (data) {
        console.log("useEffect called with real data");
    }
}, [data]);
9
  • useEffect is called once per render, is there a specific issue with that? If you just don't want to see two console logs I wouldn't worry about it and the former is ok, if the effect is doing a meaningful side-effect with data and it needs to be defined, then the latter. Commented Apr 6, 2020 at 21:28
  • Those aren't functionally equivalent. It depends on when your effect needs to trigger. Commented Apr 6, 2020 at 21:29
  • well. it triggers on every data change and data first is null and then... it has some data. will update the example to make it more clear. Commented Apr 6, 2020 at 21:31
  • I mean, you're welcome to update the question, but my response will still be the same. Neither of those is "right" and the other "wrong", they're not functionally equivalent and you need to choose one depending on what logic you need. Commented Apr 6, 2020 at 21:32
  • someServiceToFetchData sounds very effect-y to me. This should likely be within this or another effect depending on your requirements. Commented Apr 6, 2020 at 21:35

2 Answers 2

5

If you want to skip the first render you could use a state flag like this. I find the method below less complicated.

import React, { useState } from 'react';

const Comp = ({dep}) => {
    const [rendered, setRendered] = useState(false);

    useEffect(() => {
        if(rendered){
            // do stuff
        }
        
        if( ! rendered ) {
            setRendered(true);
        }
    }, [dep]);

    // rest of the component code

    return <></>
}
Sign up to request clarification or add additional context in comments.

1 Comment

For those who are facing this with the new React version, visit stackoverflow.com/questions/72238175/…
3

As we all know the useEffect is called once on initial render and also on subsequent change of values of dependency array.

In your case, to skip initial execution of useEffect (null case), write a little custom hook like which can be used generically when needed.

Component

import React,  { useState, useEffect } from 'react';
import useEffectSkipInitialRender from "./hook";

const Test = (props) => {
    const [data, setData] = useState(null);

    new Promise((res, rej) => res('my data')).then(freshData => setData(freshData));

    useEffectSkipInitialRender(() => {
        console.log("useEffect called");
    }, [data]);

    return <div>hi</div>
};

export default Test;

Custom hook

import React,  { useState, useEffect, useRef } from 'react';

const useEffectSkipInitialRender = (callback, dataArr) => {
    const [data, setData] = useState(null);
    const isInitialRender = useRef(true);// in react, when refs are changed component dont re-render 

    useEffect(() => {
        if(isInitialRender.current){// skip initial execution of useEffect
            isInitialRender.current = false;// set it to false so subsequent changes of dependency arr will make useEffect to execute
            return;
        }
        return callback();
    }, dataArr);

};

export default useEffectSkipInitialRender;

If you want effect logic to run only when data is not null and data changes, you can write your custom hook like this:

import React,  { useEffect } from 'react';

const useEffectOnDataChange = (callback, dataArr) => {
    const someIsNull = dataArr.some(data => data == null);

    useEffect(() => {
        if (someIsNull) return;
        return callback();
    }, dataArr);

}

2 Comments

Nice. But I think the PO's point is to skip when data == null instead of initial render
For those who are facing this with the new React version, visit stackoverflow.com/questions/72238175/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.