theme-ui icon indicating copy to clipboard operation
theme-ui copied to clipboard

fix: prevent unwanted rerender

Open Bram-Zijp opened this issue 3 years ago • 6 comments

I noticed that after initial render of the ThemeColorProvider, it was re-rendering.This MR prevents this re-render from taking place by populating initial color state with the localStorage cache state on first render.

Edit: It now just uses the classNames to populate initial state.

Bram-Zijp avatar Apr 25 '21 14:04 Bram-Zijp

This pull request is being automatically deployed with Vercel (learn more).
To see the status of your deployment, click below or on the icon next to each commit.

🔍 Inspect: https://vercel.com/systemui/theme-ui/HnJbs5nGMiJR6EZNZh9V4wx6ECbh
✅ Preview: https://theme-ui-git-fork-bram-zijp-fix-remove-an-unwanted-4bbf16.vercel.app

vercel[bot] avatar Apr 25 '21 14:04 vercel[bot]

Super appreciate the PR! I don't 100% understand what's happening in the new code though: why do we need to remove the body class on first render?

lachlanjc avatar Apr 25 '21 17:04 lachlanjc

At the bottom of the changed file, a class is set on the body. This specifies the initial color mode based on the local storage data, I believe. To be honest, I'm not sure if we need this "body className" in the first place. Perhaps this is something to look into. My gut feeling is that this body className is used, to consume server side rendered styles, bound to this body className.

In terms of change, the code does the exact same thing as what was implemented, with the exception of the re-render.

Why not remove classes on the useState? I believe this action will mutate the DOM while still in the process of rendering, whereas mutating the dom in the useEffect will happen after rendering of the initial DOM is complete. Correct me if I'm wrong.

Bram-Zijp avatar Apr 25 '21 17:04 Bram-Zijp

Instead of using getModeFromClass, we could specify a global on the same place we set the theme className, obtained from localStorage.. I think this will result in less LoC and better performance (noticable or not).

Bram-Zijp avatar Apr 25 '21 18:04 Bram-Zijp

Thanks for the explanation! @hasparus could you take a look?

lachlanjc avatar Apr 26 '21 15:04 lachlanjc

Thanks for the PR @Bram-Zijp! Nice catch!

@lachlanjc I'll need to take a look at corner cases (how does it look like with SSR? that rerender triggers update) and merge a few outstanding PRs to this part first (fcis' fixes).

hasparus avatar Apr 27 '21 20:04 hasparus