Skip to content
Advertisement

simple toggle hook in react

I’m having problem abstracting my toggle function out to a hook. I can make the toggle right but something is wrong in this hook code:

JavaScript

https://codesandbox.io/s/goofy-swartz-ztdfb?file=/src/App.js

what’s wrong?

Advertisement

Answer

On writing this code:

JavaScript

You actually are passing the event object to toggle function.

JavaScript

And in your custom hook, you have the condition defaultValue !== undefined which will result in a truthy value.

Therefore you should do:

JavaScript

And for your notice you can just use useReducer instead of custom hook:

JavaScript

Example of useToggle

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement