skip to Main Content

Root tag App in sandbox looks as:

import React from 'react'
import { useState, useCallback } from 'react'

export default function App() {
    let [dark, setDark] = useState(true)

    const toggleDark = useCallback(() => {
        setDark(!dark)
    }, []);

    return (
        <main>
            <p onClick={toggleDark}>{dark ? 'dark mode' : 'light mode'}</p>
        </main>
    )
}

Initial page content – "dark mode".

Press on it, changed to "light mode".

Press again on "light mode" – nothing changed. Seems state of App changed only once.

How to force state changed every time I click on <p> ?

You can see full sample at Replit sandbox

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @snaksa for correct answer


  2. You need to add dark as dependency to the useCallback. Otherwise the function is cached and always assumes that dark has the initial value of true:

    const toggleDark = useCallback(() => {
            setDark(!dark)
        }, [dark]); // add dark as dependency here
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search