Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define type to allow null in createContext React TypeScript?

I have issue about typescript when creating modal context with typescript, I want to null as default value in createContext but it will causing typescript error

import React from 'react';

type TModal = boolean;
type TModalContext = [TModal, React.Dispatch<React.SetStateAction<TModal>>];

const ModalContext = React.createContext<TModalContext | null>(null); // allow null as defaut value

const ModalProvider = ({ children }: { children: React.ReactNode }) => {
    const modalState = useState<TModal>(false);

    return <ModalContext.Provider value={modalState}>{children}</ModalContext.Provider>;
};

const useModalContext = () => React.useContext(ModalContext);

When I call useModalContext hook to use in another component I get an error:

Type ‘TModalContext | null’ is not an array type.ts(2461)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [isOpen, setOpen] = useModalContext();

How can I resolve this issue ?

>Solution :

Solution 1:

Because you tell the compile that null is a valid value, the most simple way is throw an Error when the context is null:

const useModalContext = () => {
    const context = React.useContext(ModalContext);
    if(context === null) throw new Error; // or do other things here
    return context
}

You won’t to worry about the app crashed by the Error if you always call the hook inside the context

Solution 2:

On the other hand, if you can’t ensure the hook is always safe, you should consider handle the null value from the caller:

const context = useModalContext();
const [isOpen, setOpen] = context ?? []
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading