3

I have a super simple React Typescript project using the Context API to pass down a useState hook.

export const AppContext = React.createContext(null);

function App() {
  const [value, setValue] = React.useState(3);

  return (
    <AppContext.Provider
      value={{
        value,
        setValue
      }}
    >
      <div>
        <h1>App</h1>
        <Child />
      </div>
    </AppContext.Provider>
  );
}

It's working fine on Code Sandbox: https://codesandbox.io/s/interesting-lamarr-fyy1b

However when I create a project with Create React App (npx create-react-app project-name --typescript) and try the same code I get an error:

Type '{ value: number; setValue: Dispatch>; }' is not assignable to type 'null'. TS2322

I think this is happening as null is the initial value for AppContext but is then overridden by the value passed to the Provider?

If this is the case how can I fix it? I assume one way it so relax the TypeScript settings? However is there a more elegant way of writing the code which avoids this problem? I'm new to TypeScript and the Context API so not sure if I'm doing one or both in an inadvisable way.

Evanss
  • 23,390
  • 94
  • 282
  • 505

2 Answers2

5

This is not a Typescript problem. All of you need for work to change this line:

export const AppContext = React.createContext(null);

to this line:

export const AppContext = React.createContext({});

P.s. and my advice, rewrite your Child component with AppContext.Consumer like:

const Child = () => {
  return (
      <AppContext.Consumer>
        {({ value, setValue }) => (
          <div>
            <h2>{value}</h2>
            <button onClick={() => setValue(value + 1)}>Click</button>
          </div>
        )}
      </AppContext.Consumer>
  );
};
adv0cat
  • 59
  • 2
  • With your code I get this error: Type '{ value: number; setValue: Dispatch>; }' is not assignable to type 'null'. TS2322 – Evanss Jun 25 '19 at 12:11
  • @Evanss Are you sure what in line of your code `export const AppContext = React.createContext(null);` you change `null` to `{}` – adv0cat Jun 26 '19 at 14:56
0

Have you tried to define the State like

React.useState<number|null>

?