Question
React use hooks (useContext) inside of useReducer
I have a reducer inside useContext/provider. I need to validate an action using values from another Provider. Is there a way to retrieve those values from a Provider from within the useReducer hook? Or do I have to try to feed them in as function arguments. Ex:
Reducer
export default function reducer(state: State, action: Action): State {
switch(action.type) {
case "set-amount": {
const { amount } = action.state
const { maxAmount } = useFooContext()
if (amount > maxAmount) // do something
return { ...state, amount }
}
}
}
Provider
export function Provider(...) {
const [state, dispatch] = useReducer(reducer, {}, initState)
return ...
}
=== EDIT per @Drew
Wondering if I'm following what you said, does this look right?
// provider
export default function Provider( ... ) {
const foo = useFooContext()
const fooRef = React.useRef(foo)
const reducerFn = useMemo( () => {
fooRef.current = foo
return reducer( fooRef )
}, [foo])
const [state, dispatch] = useReducer( reducerFn, {}, initState)
return ( ... )
}
// reducer
export default function(ref: React.MutableRefObject<Foo>) {
return function(state: State, action: Action): State {
...
fooRef.current.value != value
...
}
}