Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create React App with TypeScript TS2322 error with Context API + useState hook?

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.

like image 767
Evanss Avatar asked Nov 20 '25 23:11

Evanss


1 Answers

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>
  );
};
like image 150
adv0cat Avatar answered Nov 22 '25 17:11

adv0cat