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]
}
@Stringsaeed

This comment has been minimized.

Copy link

@Stringsaeed Stringsaeed commented Apr 6, 2021

you can replace any to () => void or Function

const useToggle = (initialState: boolean = false): [boolean, () => void] => {
    ...
}
@fiWhy

This comment has been minimized.

Copy link

@fiWhy fiWhy commented Jun 11, 2021

https://gist.github.com/nikasepiskveradze/9db51bc37e1c87974528b7bc47b5268c#file-use-toggle-example-ts-L16
It's not necessary to put type there. You already have predefined value.

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