Next.js Discord

Discord Forum

How to prevent Flashing Effect When Applying Custom Theme in Next.js 13

Unanswered
Cynipid gall wasp posted this in #help-forum
Open in Discord
Cynipid gall waspOP
I am relatively new to the Next/React ecosystem and currently experimenting with replicating a custom theme feature I found in a tutorial video here: https://www.youtube.com/watch?v=ahs9e4Y7ca8&t=330s&ab_channel=simonswiss (specifically, minutes 2:33 to 5:00).

In my current implementation, I fetch the theme from a database (currently hardcoded for testing purposes) and dynamically create a style tag with a custom data-theme attribute. This attribute holds variable replacements to incorporate values from the database. You can find the relevant code in the @lib/utils.ts and @components/ThemeProvider files.

However, I am encountering an issue with a flashing effect on page reloads. By default, the light theme is applied, and then my custom logic applies the intended theme, resulting in an undesirable flashing effect. I'm seeking suggestions on how to eliminate this effect.

For a better understanding, you can review my code on StackBlitz here: https://stackblitz.com/edit/stackblitz-starters-mqtgfl?file=README.md. Please navigate to "/cool-name" for a demonstration.

To clarify, the intended feature is to load a custom theme stored in a database using the slug to search for it. After retrieval, the theme should be applied, with the goal of preserving styles on page reloads or navigation to other pages.

I appreciate any insights or solutions you can provide to resolve this flashing effect issue.

Thank you!

0 Replies