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)

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 ?? []

Leave a Reply