Home > Web Front-end > JS Tutorial > body text

UseEffect How To Skip Initial Render And Only Trigger After Any Dependecy Change

DDD
Release: 2024-10-02 06:34:29
Original
1006 people have browsed it

UseEffect How To Skip Initial Render And Only Trigger After Any Dependecy Change

hope your doing well i see you got kinda frustrated with the useEffect bit but dont worry lets fix it together and solve the problem.

Why it Heppen : My dude useEffect he is really straightforward: it runs after the JSX also whenever any value in its dependency array changes. but sometimes useEffect triggers even though the data in the dependency array hasn't changed. This occurs due to the initial render.

Solution : mine could be different approcach then yours if i make any mistake please tell me and ya this works so lets dive in

Step 1 : create 2 useref in my case its componentA.tsx
We’ll use two refs to control the initial render behavior:

const skippedInitialRender = useRef(false);
const wasInitialRender = useRef(false);

Step 2 : create the useEffect

useEffect(() => {
        if(skippedInitialRender.current) {
            // After the first render, the value changes and this block will run
        }
        const currentTimeout = setTimeout(() => {
            wasInitialRender.current = true;
            skippedInitialRender.current = true;
        }, 200);
        return () => clearTimeout(currentTimeout);
    }, [value])
Copy after login

*Step 3 : * run your logic inside of the if statement and your done

*Expaination : * During the initial render, we delay execution using setTimeout. This ensures that no matter how many times useEffect triggers during the initial renders (2, 4, or more), our logic won’t run. The logic only runs when the dependency value changes again after the initial render.

The above is the detailed content of UseEffect How To Skip Initial Render And Only Trigger After Any Dependecy Change. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!