tharwi
tharwi

Reputation: 87

Run a useEffect only once when met a certain condition

I'm trying to run multiple functions inside useEffect hook. I want the functions to run after the isConnected value is resolved to a value. Its initial value is null. after a moment it will resolve into true or false. I'm considering only the first time the isConnected value is changed. The value can change over time. I have written the following code for achieving this. I want to know if is this the correct way to achieve my goal and if there are any refactors I can do to simplify this.

const App = () => {

    const {isConnected} = useNetInfo();

    const wasConnectedRef = useRef(null);

    useEffect(() => {
        if (isConnected !== null && wasConnectedRef.current === null) {
            if (isConnected) {
                functionOne();
                functionTwo();
            }
            wasConnectedRef.current = isConnected;
        }
    }, [isConnected]);

    ...
}

Upvotes: 3

Views: 4094

Answers (1)

isla_just
isla_just

Reputation: 71

I would add another useState variable that you set to true once the data has been fetched and add that as a listener in the square brackets at the end of your useEffect

Upvotes: 1

Related Questions