Skip to content

Instantly share code, notes, and snippets.



Last active Jan 10, 2021
What would you like to do?
React Hook recipe from
import React, { useReducer } from "react";
// Usage
function App(){
const [isOn, toggleIsOn] = useToggle();
return (
<button onClick={toggleIsOn}>
Turn {isOn ? 'Off' : 'On'}
// Hook
function useToggle(initialValue = false){
// Returns the tuple [state, dispatch]
// Normally with useReducer you pass a value to dispatch to indicate what action to
// take on the state, but in this case there's only one action.
return useReducer((state) => !state, initialValue);

This comment has been minimized.

Copy link
Owner Author

@gragland gragland commented Jan 9, 2021

Be sure to also check out this alternative example that shows how to create this hook with useState.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment