Forked from nikasepiskveradze/use-toggle-example.jsx
Last active
April 6, 2021 22:13
-
-
Save Stringsaeed/effee298e25bdc9947aa2095e2ad9788 to your computer and use it in GitHub Desktop.
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 { useCallback, useState } from 'react'; | |
// Usage | |
function App() { | |
// Call the hook which returns, current value and the toggler function | |
const [isTextChanged, setIsTextChanged] = useToggle(); | |
return ( | |
<button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button> | |
); | |
} | |
// Hook | |
// Parameter is the boolean, with default "false" value | |
const useToggle = (initialState = false) => { | |
// Initialize the state | |
const [state, setState] = useState(initialState); | |
// Define and memorize toggler function in case we pass down the comopnent, | |
// This function change the boolean value to it's opposite value | |
const toggle = useCallback(() => setState(state => !state), []); | |
return [state, toggle] | |
} |
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 { useCallback, useState } from 'react'; | |
// Usage | |
function App() { | |
// Call the hook which returns, current value and the toggler function | |
const [isTextChanged, setIsTextChanged] = useToggle(); | |
return ( | |
<button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button> | |
); | |
} | |
// Hook | |
// Parameter is the boolean, with default "false" value | |
const useToggle = (initialState: boolean = false): [boolean, () => void] => { | |
// Initialize the state | |
const [state, setState] = useState<boolean>(initialState); | |
// Define and memorize toggler function in case we pass down the comopnent, | |
// This function change the boolean value to it's opposite value | |
const toggle = useCallback((): void => setState(state => !state), []); | |
return [state, toggle] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment