Created
April 3, 2023 04:02
-
-
Save jhavenz/9c37fb71dc1b5e683d0c34819898ecbe to your computer and use it in GitHub Desktop.
useToggle React Hook
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
# |
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, { useState } from 'react' | |
export default function useToggle(defaultValue = false) { | |
const [value, setValue] = useState(defaultValue) | |
function toggleValue(value) { | |
setValue((currentValue) => | |
typeof value === 'boolean' ? value : !currentValue | |
) | |
} | |
return [value, toggleValue] | |
} |
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 useToggle from '@/hooks/useToggle/useToggle' | |
import React from 'react' | |
export default function UseToggleExampleComponent() { | |
const [value, toggleValue] = useToggle(false) | |
return ( | |
<div> | |
<div>{value.toString()}</div> | |
<button onClick={toggleValue}>Toggle</button> | |
<button onClick={() => toggleValue(true)}>Set to true</button> | |
<button onClick={() => toggleValue(false)}>Set to false</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment