4 ms·
NullComponents and UseLayoutEffect Hook
Sometimes you have to create Null Components (components returning no useful element, <></>) in your project, to use the existing code.
Recently, I had to use an existing custom hook to fetch some info and store it, on an array map traversal. Thought to create Null Components for that.
And, also find out that sometimes you need useLayoutEffect and not useEffect in your code.
I was using useEffect to initialize the state of loading in the context provider and had to set the loading to false once I got the info from the Null Components.
But the useEffects (used for fetching the info) in the Null Components were running before the context provider useEffect (after child renders - run its effect - after this the parent rendering gets completed - now run its effect), and that's why the loading state initialization was happening when it was not needed. And that was causing the UI issues.
As we know that useLayoutEffect runs before the browser paints anything to the screen (and useEffect after the browser's done with painting), so we can initialize the loading state in the useLayoutEffect hook in the context provider, and it will run before the useEffects in the Null Components. Hence we have our loading state initialized correctly. And that will solve the UI issues, we were facing.