React useToggler hook
React, Hooks, State, Callback · Nov 27, 2020

Provides a boolean state variable that can be toggled between its two states.
- Use the
useState()
hook to create thevalue
state variable and its setter. - Create a function that toggles the value of the
value
state variable and memoize it, using theuseCallback()
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.createRoot(document.getElementById('root')).render(
<Switch />
);
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.