I want to create a React Context and pass state
and setState
properties useState
Hook down to a Consumer.
I have a Step
and a Context
types:
type Step = {
step: string;
};
type Context = {
step: Step;
setStep: Dispatch<SetStateAction<Step>>;
};
I create a context:
export const StepContext = createContext<Context | undefined>(undefined);
I create a StepProvider
and a hook:
const StepProvider = ({ children }: { children: ReactNode }) => {
const [step, setStep] = useState<Step>({ step: 'one' });
return <StepContext.Provider value={{ step, setStep }}>{children}</StepContext.Provider>;
};
I create a StepConsumer
:
const StepConsumer = () => {
const { step, setStep } = useContext(StepContext);
return <div>{...}</div>;
};
But in:
const { step } = useContext(StepContext)
step
and setStep
return the following error TS2339: Property 'step' does not exist on type 'Context | undefined'
Am I not passing the types the right way?
Thanks