Files
30-seconds-of-code/snippets/useToggler.md
Isabelle Viktoria Maciohsek 2af2490ca8 Bake dates into snippets
2021-06-13 19:44:42 +03:00

924 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
useToggler hooks,state,callback,beginner 2020-11-27T09:41:31+02:00 2020-11-27T09:41:31+02:00

Provides a boolean state variable that can be toggled between its two states.

  • Use the useState() hook to create the value state variable and its setter.
  • Create a function that toggles the value of the value state variable and memoize it, using the useCallback() hook.
  • Return the value state variable and the memoized toggler function.
const useToggler = initialState => {
  const [value, setValue] = React.useState(initialState);

  const toggleValue = React.useCallback(() => setValue(prev => !prev), []);

  return [value, toggleValue];
};
const Switch = () => {
  const [val, toggleVal] = useToggler(false);
  return <button onClick={toggleVal}>{val ? 'ON' : 'OFF'}</button>;
};
ReactDOM.render(<Switch />, document.getElementById('root'));