Home > Net >  How to type the initial state for react context when using useState as value
How to type the initial state for react context when using useState as value

Time:04-23

I recently saw a youtube video by Jack Herrington, "Mastering React Context" where he used useState as a value for his context provider. This struck me as interesting but when i tried doing the same with typescript i was stumped completely by how to type the initial state.

Example JS code:

const CounterContext = createContext(null);

const CounterContextProvider = ({children}) => {
  return (
    <CounterContext.Provider value={useState(0)}>
      {children}
    </CounterContext.Provider>
}  

Using null as default value is out of the question. I could define the correct types for useState but what would the initial state values look like?

CodePudding user response:

The value returned by useState(0) is a tuple of type [number, Dispatch<SetStateAction<number>>], where Dispatch and SetStateAction are imported from react. So with a mock default value, that will look like:

import { createContext, Dispatch, SetStateAction } from "react";

const CounterContext = createContext<
  [number, Dispatch<SetStateAction<number>>]
>([0, () => {}]);

  • Related