diff --git a/snippets/useToggler.md b/snippets/useToggler.md new file mode 100644 index 000000000..d06e2807a --- /dev/null +++ b/snippets/useToggler.md @@ -0,0 +1,28 @@ +--- +title: useToggler +tags: hooks,state,callback,beginner +--- + +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. + +```jsx +const useToggler = initialState => { + const [value, setValue] = React.useState(initialState); + + const toggleValue = React.useCallback(() => setValue(prev => !prev), []); + + return [value, toggleValue]; +}; +``` + +```jsx +const Switch = () => { + const [val, toggleVal] = useToggler(false); + return ; +}; +ReactDOM.render(, document.getElementById('root')); +```