Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active January 10, 2021 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gragland/49a5d8d354b59b939f91d5510affad53 to your computer and use it in GitHub Desktop.
Save gragland/49a5d8d354b59b939f91d5510affad53 to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
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);
}
@gragland
Copy link
Author

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