0

I am want to provider useReducer globally, but createContext() is asking for default value, which is throwing error if I assign null. I have tried assigning empty object instead of null. But I cannot access my userReducer if I do it this way.

import React, { createContext, useContext, useReducer, Dispatch } from "react";
import { reducer, initialState } from "./reducer";

const AppContext = createContext(null)

export const useAppContext = () => useContext(AppContext)

export const AppContextProvider: React.FC = ({children}) => (
    <AppContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </AppContext.Provider>
)

How can I solve the issue?

Sardorek Aminjonov
  • 724
  • 2
  • 7
  • 16
  • Where are the types? You didn't type anything, are you just asking how to type useReducer? There are plenty of similar questions – Dennis Vash Apr 25 '21 at 14:48
  • You should type your context too `createContext(null)` – Dennis Vash Apr 25 '21 at 14:50
  • I am new to ts. I can do it without ts. But I want to know how it can be done with ts. I want a clue! – Sardorek Aminjonov Apr 25 '21 at 14:54
  • The way you wrote it, it confused the heck of me :) Basically you are asking how to do `value={array}` since `useReducer` returns an array. If you can write `const [state, dispatch] = useReducer(...)`, it'll help you figure out the missing type. – windmaomao Apr 25 '21 at 15:04
  • A side question, is `Context` + `useReducer` essentially `redux`? (not fan of redux). I found the above code a good replacement of `redux`. If you happen to have the answer, thank you. – windmaomao Apr 25 '21 at 15:07
  • @windmaomao There are similarities, but also differences. [Context](https://reactjs.org/docs/context.html) is distinct from redux so I wouldn't recommend conflating the two. [useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer) can definitely be thought of with similar concepts to redux's reducers, but there are certain differences such as no middleware for useReducer. – mcy Apr 25 '21 at 15:28

0 Answers0