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
Thanks to @snaksa for correct answer
You need to add
dark
as dependency to theuseCallback
. Otherwise the function is cached and always assumes thatdark
has the initial value oftrue
: