How to use React Context's with Hooks?

Viewed 173

In my application, I'm trying to use React Context's with setState.

const userContext = React.createContext([{ user: {} }, () => {}]);
const userHook = useState({ user: {} });

<userContext.Provider value={userHook}>
// some other code here
</userContext.Provider>

However, I'm getting this error in my linter: enter image description here.

Could anyone point me in the right direction?

Also, when I try to use React.createContext() like in many tutorials, e.g.:

const ThemeContext = createContext(["green", () => {}]);

I get another linter error about an unexpected empty arrow function. How do I fix that?

2 Answers

You need to fix the typings of the context you are creating:

import { Dispatch, SetStateAction } from "react";

const userContext = createContext<
  [{ user: {} }, Dispatch<SetStateAction<{ user: {} }>>]
>([{ user: {} }, () => {}]);

Now, you won't see any Type error when providing it using:

const userHook = useState({ user: {} });
// ...
<userContext.Provider value={userHook}>
  <Foo />
</userContext.Provider>

Remember that userHook will be an array which you may destructure as:

function Foo() {
  const userHook = useContext(userContext);
  const [user, setUser] = userHook // Here, destructuring the array
  return <h1>Foo</h1>;
}

const userHook = useState({ user: {} }); is wrong. useState returns [state, setState]. Try changing the implementation.

const [state, setState] = useState({ user: {} });

<userContext.Provider value={state}>
// some other code here
</userContext.Provider>
Related