raddix

useToggle

A hook that toggles a boolean value.

Installation

Install the custom hook from your command line.

npm i @raddix/use-toggle

Usage

Basic example

In this example, we are going to expand or hide the text of a paragraph. by clicking a button (read more/read less).

import { useToggle } from '@raddix/use-toggle';
export const Example = () => {
const [show, setShow, toggle] = useToggle();
return (
<div>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto
animi pariatur quod harum impedit beatae dicta, tempore, explicabo
laborum ducimus eligendi porro? Odit vero perferendis facere eius totam
saepe dolores?
</p>
{show && (
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Rerum earum
dolore, nostrum esse sint nobis facere consequuntur placeat harum
molestiae unde ad laudantium reiciendis, a tempore eos, sunt quasi
quo.
</p>
)}
<span onClick={toggle}>{!show ? 'Read more...' : 'Read less'}</span>
</div>
);
};

API

Result

The useToggle hook returns an array with the following elements:

IndexDescriptionType
0The current value of the state.boolean
1A function to change the state.function
2A function to toggle the state.function

Parameters

NameDescriptionRequiredDefault ValueType
initialValueThe initial value of the boolean state.Nofalseboolean