Garrit's Notes

Quick tip! React useToggle Hook

Dec 21 2021

Here's a useful react hook for situations where you have to keep track of the state of a dialog, popup, etc.:

import { useState } from 'react';

export default (value) => {
    const [state, setState] = useState(value);

    const setStateActive = () => {
        setState(true);
    };

    const setStateInactive = () => {
        setState(false);
    };

    return [
        state,
        setStateActive,
        setStateInactive,
    ];
};

Usage:

const SomeComponent = () => {
    const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useToggle(false);

    return (
        <>
            <Button onClick={openDeleteDialog}>Open Delete Dialog</Button>
            <Dialog isOpen={isDeleteDialogOpen} onClose={closeDeleteDialog}></Dialog>
        </>
    );
};

This is post 021 of #100DaysToOffload.


If you enjoyed this post, consider buying me a coffee! Got comments? Send me a Mail, or shoot me a message on Matrix.