DEV Community

Discussion on: useToggle: Custom react hook for toggle

moresaltmorelemon profile image
Ezra Schwepker • Edited on

Consider using useCallback

const toggle = useCallback(() => setVisibility((prev) => !prev), []);

return [visible, toggle, setVisibility];
Enter fullscreen mode Exit fullscreen mode
import { useCallback } from 'react';
import { useToggle } from "./useToggle";

const App = () => {
  const [visible, toggleVisibility, setVisibility] = useToggle(false);
  const hide = useCallback(() => setVisibility(false), []);

  return (
        <button onClick={toggleVisibility}>Toggle</button>
        <button onClick={hide}>Hide</button>

      <div>{visible ? "Hello" : "Hidden content"}</div>
Enter fullscreen mode Exit fullscreen mode

While not strictly necessary, not doing so creates a new callback function every single time useToggle is evaluated (as does defining a callback in the onClick={() => ...} props), which means every time a component receives the new callback function, it re-renders, even though nothing about the callback actually changed.

318097 profile image
Mehul Lakhanpal Author

Great. Thanks for the suggestion and the efforts to update the example :) :)