Reputation: 108
Similar question posted on Arrow functions only have access to initial state created by useReducer, not updated state but not resolved.
The state (useReducer) is not reflected in arrow functions.
A simple example: React component
const Component = ({ children }: Props) => {
const [state, dispatch] = useReducer(reducer, {visitor: false})
useEffect(() => {
someObject = new Connection({
onMessage: msg
onSuccess: () => dispatch({type: "Visitor", value: true})
})
return () => console.log("UNMOUNTING ");
}, []);
const msg = (request) => {
// visitor: false
console.log(state) // expected updated state, but instead see initial state, why?
// ... do more things
}
// visitor: true
console.log(state) // updated state is present here
return (
<Component.Provider value={{ state }}>
{children}
</Component.Provider>
)
}
Reducer function:
const reducer = (state, action) => {
switch (action.type) {
case 'Visitor':
return {...state, visitor: true}
default:
return state
}
}
Upvotes: 0
Views: 602
Reputation: 53914
You are passing a callback to useEffect
on component mount, this callback has a closure on state
value {visitor: false}
.
// Closure on `state = {visitor: false}` passed to useEffect
useEffect(() => {
msg();
}, [])
Upvotes: 1