Last active
January 10, 2021 00:11
-
-
Save gragland/49a5d8d354b59b939f91d5510affad53 to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer } from "react"; | |
// Usage | |
function App(){ | |
const [isOn, toggleIsOn] = useToggle(); | |
return ( | |
<button onClick={toggleIsOn}> | |
Turn {isOn ? 'Off' : 'On'} | |
</button> | |
); | |
} | |
// 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be sure to also check out this alternative example that shows how to create this hook with useState.