1001 B
1001 B
title, tags, expertise, author, cover, firstSeen, lastUpdated
| title | tags | expertise | author | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|---|
| React useToggler hook | hooks,state,callback | beginner | chalarangelo | blog_images/tram-car-2.jpg | 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 thevaluestate variable and its setter. - Create a function that toggles the value of the
valuestate variable and memoize it, using theuseCallback()hook. - Return the
valuestate 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'));