simple toggle hook in react

Tags: ,



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:

import { useState, useCallback } from "react";

const useToggle = (initialValue = false) => {
  const [value, setValue] = useState(initialValue);

  const toggle = useCallback((defaultValue) => {
    defaultValue !== undefined
      ? setValue(defaultValue) //set true or false
      : setValue((value) => !value); //if param is not supplied, toggle the value
  }, []);

  return [value, toggle];
};

export default useToggle;

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

what’s wrong?

Answer

On writing this code:

<button onClick={toggle}>toggle</button>

You actually are passing the event object to toggle function.

onClick={(event) => toggle(event)}
// Same
onClick={toggle}

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

Therefore you should do:

<button onClick={() => toggle()}>toggle</button>

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

const [value,toggle] = useReducer(p=>!p, false);

Example of useToggle

const useToggle = (initialValue = false) => {
  const [value, setValue] = useState(initialValue);
  const toggle = useCallback(() => setValue((value) => !value), []);
  return [value, toggle];
};


Source: stackoverflow