useState()
hook to create the value
state variable and its setter.value
state variable and memoize it, using the useCallback()
hook.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'));
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️