Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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]
}
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, any] => {
// 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]
}
@pvaskria
Copy link

pvaskria commented Oct 5, 2021

Fix the typo from
// Define and memorize toggler function in case we pass down the comopnent,
to
// Define and memorize toggler function in case we pass down the component,

@roansong
Copy link

roansong commented Dec 15, 2021

And on the line after that:
// This function change the boolean value to it's opposite value
to
// This function changes the boolean value to its opposite value

@flyingangel
Copy link

flyingangel commented Dec 29, 2021

While setState(state => !state) is valid. It violated the rule "no-shadow" of Eslint : https://eslint.org/docs/rules/no-shadow

The variable name state should be changed.

@jhildensperger
Copy link

jhildensperger commented Apr 3, 2022

The typo, comopnent component, seems to be fixed in the .jsx, but not the .ts

// Define and memorize toggler function in case we pass down the comopnent

@ivxvm
Copy link

ivxvm commented Jun 13, 2022

setIsTextChanged is imo a bad name for toggler function. toggleIsTextChanged would be better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment