Last active
April 2, 2020 15:35
-
-
Save patmaddox/eb58d90c97dfd9fa304e8499f6ff26fd to your computer and use it in GitHub Desktop.
toggles and hooks
This file contains 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 { useState, useCallback } from 'react'; | |
export default function useToggle(initialState) { | |
const [isOn, setIsOn] = useState(initialState); | |
const turnOn = useCallback(() => setIsOn(true), [setIsOn]); | |
const turnOff = useCallback(() => setIsOn(false), [setIsOn]); | |
const toggle = useCallback(() => setIsOn(prevState => !prevState), [setIsOn]); | |
return { isOn, turnOn, turnOff, toggle, setIsOn }; | |
} |
This file contains 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
function toggle(initialValue, callback) { | |
let value = initialValue; | |
const isOn = function() { | |
return value; | |
} | |
const setIsOn = function(newValue) { | |
value = newValue; | |
callback(value); | |
} | |
const turnOn = function() { | |
setIsOn(true); | |
} | |
const turnOff = function() { | |
setIsOn(false); | |
} | |
const toggle = function() { | |
setIsOn(!value); | |
} | |
return { isOn, turnOn, turnOff, toggle, setIsOn } | |
} | |
class MyComponent extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
toggleValue: false | |
} | |
this.toggle = toggle(this.state.toggleValue, newValue => this.setState({ toggleValue: newValue })) | |
} | |
} |
This file contains 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
function toggleHook(initialState) { | |
const [isOn, setIsOn] = useState(initialState); | |
const theToggle = toggle(initialState, setIsOn); | |
return { isOn, turnOn: theToggle.turnOn, turnOff: theToggle.turnOff, toggle: theToggle.toggle } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment