Search code examples
javascriptreactjstypescripteslintuse-context

What's the proper type declaration of React context functions to avoid linting issues?


I am using React Context and I have:

const DocumentContext = createContext<
    [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>([initVal, () => { }, () => { }]);

But my linter complains:

Unexpected empty arrow function @typescript-eslint/no-empty-function

I know I can turn that off in my linting settings, but is there a right way to do it?


Solution

  • If you're looking only to suppress linter message you may declare it as:

    const DocumentContext = createContext<
        [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
    >([initVal, () => { /* do nothing */ }, () => { /* do nothing */ }]);
    

    or as:

    const DocumentContext = createContext<
        [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
    >([initVal, () => undefined, () => undefined]);
    

    If you're absolutely sure you're not going to use this default value anywhere. i.e you don't have components using this context beyond this context's provider you may simply define it as:

    const DocumentContext = createContext<
        [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
    >(null as any);