Menu

gitpiper

useToggler react Code Snippet in 2022

hooksstatecallbackbeginner

Last Updated: 25 September 2022

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'));

react snippet similar to useToggler For You in September 2022

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2022 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️