Search code examples
reactjstypescriptreact-context

Type 'Dispatch<hook>' is not assignable to type '() => void'


I tried looking through similiar questions and articles but nothing really seemed to work. I'm also somewhat at a loss as to what the error means since I tried to set a value and tried to declare a type but neither worked.

import React, { createContext, SetStateAction, useState } from 'react';

export const MenuContext = createContext({
    open: false,
    setOpen: () => {},
});
export default function MenuManager(props:any) {
    const [open, setOpen] = useState(false);
    return (
        <MenuContext.Provider value={{ open, setOpen }}>
            {props.children}
        </MenuContext.Provider>
    );
}

The error is gives back is

Type 'Dispatch<SetStateAction<boolean>>' is not assignable to type '() => void'.

Solution

  • Declare an interface for the MenuContext and correctly type the context and setOpen state updater function.

    Example:

    import React, { createContext, SetStateAction, useState, Dispatch } from 'react';
    
    interface IMenuContext {
      open: boolean;
      setOpen: Dispatch<SetStateAction<boolean>>;
    }
    
    export const MenuContext = createContext<IMenuContext>({
      open: false,
      setOpen: () => {},
    });
    

    Also, instead of any you'll want to type the ManuManager component's props.

    function MenuManager(props: React.PropsWithChildren<{}>) {
      const [open, setOpen] = useState(false);
      return (
        <MenuContext.Provider value={{ open, setOpen }}>
          {props.children}
        </MenuContext.Provider>
      );
    }