From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Dark/light mode persisting

Dark/light mode persisting

In this session, you will learn how to implement persistent dark light mode in your React application. This means the user's preferred theme will be saved and automatically applied even after they close and reopen the browser. We'll achieve this using Local Storage, a web storage API available in modern browsers. Now, I am adding persistence to our theme using localStorage. I added a function getInitialTheme() which attempts to retrieve the theme from localStorage using localStorage.getTheme(). If a theme is found in localStorage, it is used. If not, it defaults to light. This is important so the user isn't stuck in dark mode if they haven't set a preference yet. I am modifying the useState hook to use the getInitialTheme function. Instead of hard-coding dark as the initial state, I call getInitialTheme. This ensures that the theme is initialized from local storage if available, providing a persistent theme experience for the user. Now it is time to save the theme to local storage…

Contents