useToggle
Basically, what this hook does is that, it takes a parameter with value true or false and toggles that value to opposite. It's useful when we want to take some action into it's opposite action, for example: show and hide modal, show more/show less text, open/close side menu.
Usage
import { useState } from 'react';
type UseToggleReturnType = [boolean, () => void];
const useToggle = (initialValue: boolean): UseToggleReturnType => {
const [value, setValue] = useState<boolean>(initialValue);
const toggleValue = () => {
setValue((prevValue) => !prevValue);
};
return [value, toggleValue];
};
export default useToggle;
Here's how you can use the useToggle
hook in a React component:
import { useState } from 'react';
import useToggle from './useToggle';
const ExampleComponent = () => {
const [isEnabled, toggleEnabled] = useToggle(false);
return (
<div>
<p>The toggle is currently {isEnabled ? 'enabled' : 'disabled'}.</p>
<button onClick={toggleEnabled}>Toggle</button>
</div>
);
};
export default ExampleComponent;
In this example, the useToggle
hook takes an initialValue
boolean as an argument and returns an array with two items: the current boolean value and a function to toggle the value. The ExampleComponent
uses this hook to toggle a boolean value and render a message based on the current state of the value.
Last updated