The dark mode class in Next.js/React does not take effect until a local change is made

I've been diving into a helpful tutorial on implementing dark mode toggle in my project. The tutorial uses react-toggle and can be found here. Everything seems to be working fine except for one issue that arises on the initial page load.

When the browser has 'prefers-color-scheme: dark', the dark mode toggle doesn't receive the 'react-toggle--checked' class until I make a local change in VSCode and save it. Only then does the class get applied properly.

Before saving:

After saving:

I'm puzzled as to why this behavior is occurring. The initial value of 'isDark' is true, hence the Toggle's 'checked' value should also be true and trigger the application of the 'react-toggle--checked' class. Why does making a local change in the editor and saving fix this issue?

The technologies being used are Next.js and React.

useColorScheme.js


import { useEffect, useMemo } from 'react'
import { useMediaQuery } from 'react-responsive'
import createPersistedState from 'use-persisted-state'

const useColorSchemeState = createPersistedState('colorScheme')

export function useColorScheme() {
  const systemPrefersDark = useMediaQuery(
    {
      query: '(prefers-color-scheme: dark)',
    },
    undefined,
  );

  const [isDark, setIsDark] = useColorSchemeState()

  const value = useMemo(() => isDark === undefined ? !!systemPrefersDark : isDark,
    [isDark, systemPrefersDark])

  useEffect(() => {
    if (value) {
      document.body.classList.add('dark')
    } else {
      document.body.classList.remove('dark')
    }
  }, [value])

  return {
    isDark: value,
    setIsDark
  }
}

ColorSchemeToggle.js


import Toggle from 'react-toggle'
import { useColorScheme } from './useColorScheme'

// Styles
import 'react-toggle/style.css'

const ColorSchemeToggle = () => {
    const { isDark, setIsDark } = useColorScheme()

    return (
        <Toggle
            checked={isDark}
            onChange={({ target }) => setIsDark(target.checked)}
            aria-label='Dark mode toggle'
            className={`dark-mode-toggle`}
        />
    )
}

export default ColorSchemeToggle

Answer №1

It seems that the usepersistedstate library utilizes localstorage as its default storage mechanism.

Visit this link for more information

The use-persisted-state library functions as a factory rather than a hook itself. It requires a storage key and optional storage provider (default = localStorage) to return a hook that can be seamlessly integrated as a replacement for useState.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do I eliminate the MuiClockPicker-arrowSwitcher from my TimePicker component?

I'm facing an issue with removing the '<' and '>' characters in my TimePicker component. Below is a snippet of my code: <LocalizationProvider dateAdapter={AdapterDateFns}> <TimePicker {...field} openTo="hour ...

Ways to eliminate the .html extension when someone accesses your static website

My current setup involves a static website being served by nginx. For example, when visiting www.mydomain.com, it displays as www.mydomain.com/index.html. Is there a way to avoid the trailing .html and have www.mydomain.com/index displayed instead? I&ap ...

Pattern matching system to replace only the single occurrence of a character preceding a particular sequence

I have a lot of HTML code that looks like this: <a href="http://example.com/project-a" title="Project A (test)">Project A (test</span></a> <a href="http://example.com/project-b" title="Project B (test)">Project B (test</span> ...

Creating a script to open multiple URLs in HTML and JavaScript

Currently, I am working on creating a multiple URL opener using HTML and JavaScript. However, I have encountered an issue where HTTP links are opening fine but HTTPS links are not. Can someone provide assistance with this problem? Below is the code snippet ...

I'm having trouble getting my modal to open, it just displays the information on my page instead

I am encountering some difficulties with my model window. I would like it to open a modal that shows a larger version of the photo and description when the thumbnail is clicked. However, I have not been able to get it to work properly. The only time it pop ...

Is it possible to leverage Create-React-App's npm start in conjunction with Node.js?

I've recently started diving into React and node.js. My goal is to have a node.js server that can serve up React.js pages/views. After running 'create-react-app' and then using 'npm start', I'm not sure if I also need to man ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...

Tips for displaying only one image when clicked and hiding other divs:

Currently tackling a project that involves JavaScript and I've hit a roadblock. Before you dive into the text, take a look at the image. Check out the picture here. I have successfully created a slider, but now I want to implement a feature where cli ...

The issue of Ajax failing to execute an HTTP POST request in an HTML environment

I am creating a sample HTML code that involves making HTTP post requests using an Ajax function. The task at hand is to execute 2 HTTP POST requests and 1 GET request sequentially based on the correct response received. POST: URL: http://localhost:8082 ...

Utilize Python (specifically with the Pillow library) to remove transparent backgrounds

When using the python module html2image to convert html to an image, I encountered an issue with fixed image size causing the html to break or get cut off, leaving a blank space. Is there a Python-based solution to fix this problem? (I am using chat export ...

The React.js .map function encountered an error while trying to map the results from Firebase

As a newcomer to the realm of React and Firebase, I find myself struggling with arrays and objects. It seems like the way my data is formatted or typed does not play well with the .map method. Despite scouring Stack Overflow for answers, none of the soluti ...

Encountering a Next.js hydration issue when trying to map an icon

Encountering a hydration error while using next js I'm facing a hydration error within the div where I incorporated the star icon. Despite trying to implement useEffect as suggested in the documentation, the issue persists. ...

Retrieving information from a repository through a Rest API

Whenever I attempt to retrieve my data from the repository and log it in the console, the array seems to be empty. Here is a snapshot of the data repo: https://i.stack.imgur.com/ftCBm.png Here is the code snippet from server.js: import express from &apos ...

ReactJS - Charts from ChartJS are continuously refreshing after the initial page load

I'm currently working on a project that requires the use of charts, so I decided to utilize chartsjs. However, I am encountering a small issue that has two components. https://i.stack.imgur.com/00Of0.gif Upon initial page load, my data is not displ ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

Combine React 17 with webpack 5 and babel-plugin-react-css-modules, enabling the use of CSS modules with stylename functionality

I am in the process of setting up a new React application using the latest technologies available, including React 17, Webpack 5, and other essential modules. My goal is to implement CSS modules utilizing the styleName concept with the help of babel-plugi ...

Setting a global variable in the JavaScript code below

Is there a way to make the modal variable global by setting it as var modal = $("#modal"); ? The code snippet below includes the modal variable and is not functioning properly. It needs to work correctly in order to display: "Hello name, You have signed u ...

React: You can start the project with npm start successfully, but if you try to build it using npm run build, it throws an EL

My React application, built using create-react-app, has been running smoothly with npm start. A few days ago, I successfully deployed it to Firebase hosting using npm run build. However, today I encountered an issue where npm run build throws the followin ...

What are the steps for encoding a value using jquery serialize?

I attempted to encode all values using the following code: encodeURIComponent($("#customer_details").serialize()); Unfortunately, it did not produce the desired results. Is there a method to retrieve all elements on a form and individually encode each v ...

Discrepancy in Angular Material Buttons with theme design

I recently installed Angular 10 along with Angular Materials using the command ng add @angular/material I opted for the custom theme: Purple/Green The next step was to add a Toolbar by simply copying and pasting code from Google's site. However, I a ...