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])
*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!