useState() semantic when you need to toggle modal visibility

RMAG news

The problem

Is not a real problem but is something about semantic in use state variabile using useState(). The fact is useState() can be used to store if a modal is open or close. What I HATE is use the setter in this way: const [isOpen, setOpen] = useState(false);. What I hate is the use of setOpen. I prefer a more semantic way to manage boolean values.

Type

useState() returns two values. First with the boolean value and second the method to update the variable.

type Modal = [boolean, () => void, () => void];

Solution

My proposal is to stop using useState() and start building hooks like this one. If the semantic is to open or close a modal… just provide

isOpen
openModal()
closeModal()

Code

type Modal = [boolean, () => void, () => void];

const useModal = (initial: boolean): Modal => {
const [isModalOpen, setValue] = useState(initial);
const open = () => setValue(true);
const close = () => setValue(false);
return [isModalOpen, open, close];
};

export default function Home() {
const [isFirstModalOpen, openFirstModal, closeFirstModal]
= useModal();
}

Conclusion

This is a little example but this hook can now be used for all the modals:

const [isSomethingOpen, openSomething, closeSomething]
= useModal();

The book (only for italian speakers)

This and others snippets will be included in next edition of React, TypeScript e Next.js. Please follow me as author to receive notifications of new books (React 19 is coming)!!

Leave a Reply

Your email address will not be published. Required fields are marked *