DEV Community

Discussion on: useToggle: Custom react hook for toggle

Collapse
 
moresaltmorelemon profile image
Ezra Schwepker • Edited

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 (
    <div>
      <div>
        <button onClick={toggleVisibility}>Toggle</button>
        <button onClick={hide}>Hide</button>
      </div>

      <div>{visible ? "Hello" : "Hidden content"}</div>
    </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.

Collapse
 
ml318097 profile image
Mehul Lakhanpal

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