Search code examples
reactjstypescriptreact-context

React useContext TS typing state setter


I'm trying to setup a context provider for a parent component:

import React from "react";

export type RootStackParamList = {
  Home: undefined;
  ReactQuiz: undefined;
};

type Score = {
  correct: number,
  incorrect: number
}

export type ReactQuizContextType = {
  score: Score;
  setScore: (score: Score) => void;
}

export const ReactQuizContext = React.createContext<ReactQuizContextType>({
  score: {
    correct: 0,
    incorrect: 0
  },
  setScore: () => void
})

export const useReactQuizContext = () => React.useContext(ReactQuizContext);

But I'm not sure how to type the setScore function, I'll be passing the following state as a value to the provider:

  const [score, setScore] = React.useState({
    correct: 0,
    incorrect: 0,
  });

But I can't type the function in the context using the same type ts is giving me:

React.Dispatch<React.SetStateAction<{
    correct: number;
    incorrect: number;
}>>

I tried typing the function with:

() => void;

and

(score: Score) => void

but that doesn't seem to work either. Any ideas?


Solution

  • The type that you are trying to use for the setScore is correct. The problem is with the initial value of it. void is not a valid thing in Javascript.

    You can replace it with:

    setScore: () => {},