Does a render happen before function in React Hooks useEffect is called?

0

Issue

I would have thought that useEffect’s first function gets called before the first render, but when I call the method below, my console.log just before the return method call gets called, then the useEffect’s first parameter function gets called.

order of calls:

just before render return
ImageToggleOnScroll.js:8 useEffect before setInView
ImageToggleOnScroll.js:10 useEffect after setInView

Source:

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

// primaryImg is black and white, secondaryImg is color
const ImageToggleOnMouseOver = ({ primaryImg, secondaryImg }) => {
    const imageRef = useRef(null);

    useEffect(() => {
        console.log('useEffect before setInView')
        setInView(isInView());
        console.log('useEffect after setInView')
        window.addEventListener("scroll", scrollHandler);

        return () => {
            window.removeEventListener("scroll", scrollHandler);
        };
    }, []);

    const isInView = () => {
        if (imageRef.current) {
            const rect = imageRef.current.getBoundingClientRect();
            return rect.top >= 0 && rect.bottom <= window.innerHeight;
        }
        return false;
    };

    const [inView, setInView] = useState(false);
    const scrollHandler = () => {
        setInView(() => {
            return isInView();
        });
    };

    console.log('just before render return')
    return (
        <img
            ref={imageRef}
            src={inView ? secondaryImg : primaryImg}
            alt="image here"
        />
    );
};

export default ImageToggleOnMouseOver;

Solution

Effects created using useEffect are run after the render commit phase and hence after the render cycle. This is to make sure that no side-effects are executed during the render commit phase which might cause inconsistency

According to the documentation

Mutations, subscriptions, timers, logging, and other side effects are
not allowed inside the main body of a function component (referred to
as React’s render phase). Doing so will lead to confusing bugs and
inconsistencies in the UI.

The function passed to useEffect will run
after the render is committed to the screen.

useEffect hook can be used to replicate behavior of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods for class components depending the arguments passed to the dependency array which is the second argument to useEffect and the return function from within the callback which is executed before the next effect is run or before unmount

For certain useCases such as animations you may make use of useLayoutEffect which is executed synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

Answered By – Shubham Khatri

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More