DEV Community

loading...

Discussion on: I Used React Context To Enable Dark Mode

Collapse
frontendphil profile image
Philipp Giese • Edited

Hey there :) Every time I see a function that is called toggleSomething and then accepts a parameter I make this comment. I'd either rename it to setSomething if it accepts a parameter or remove the need for the param instead. In your example you could achieve it like this:

const toggleDark = useCallback(() => {
  setDark((dark) => !dark)
}, [])
Enter fullscreen mode Exit fullscreen mode

FYI I've used useCallback so that the function does not change every time the context provider renders. This way consumers do not need to update necessarily even though nothing has changed.

Collapse
sanliverpool13 profile image
sanliverpool13 Author

Hey Philipp, thank you for the tip! Your code is much cleaner and makes much more sense for that function. Duly noted! And yes I understand your use of useCallback, so that the function is not redefined on every render of the component. Thank you for taking your time to read my article. Appreciate it!

Forem Open with the Forem app