Reputation: 11981
I'm trying to rerender {userNumbers}
in ChildScreen. I managed to add userNumbers
state in Home, but it doesn't rerender the text.
UserContext.js
import { createContext } from 'react';
export const UserContext = createContext(null);
Home.js
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import { UserContext } from "../contexts/UserContext";
import ChildScreen from "ChildScreen";
const Stack = createStackNavigator();
export default function Home() {
const [state, dispatch] = React.useReducer((prevState, action) => {
switch (action.type) {
case 'ADD_USER':
return {
...prevState,
users: state.users + action.newUsers
};
}
}, {
users: 0
});
const userContext = React.useMemo(
() => ({
addUsers: async data => {
dispatch({
type: 'ADD_USER',
newUsers: data.newUsers
});
},
userNumbers: state.users
}),
[]
);
return (
<UserContext.Provider value={userContext}>
<Stack.Navigator>
<Stack.Screen name="ChildScreen" component={ChildScreen} />
</Stack.Navigator>
</UserContext>
)
}
ChildScreen.js
import React from 'react';
import { View, Text } from 'react-native';
import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import { UserContext } from "../contexts/UserContext";
export default function ChildScreen() {
const { addUsers, userNumbers } = React.useContext(UserContext);
render (
<View><Text>{userNumbers}</Text></View>
<TouchableWithoutFeedback onPress={() => { addUsers({newUsers: 999)}) }>
<Text>Add 999 Users</Text>
</TouchableWithoutFeedback>
)
}
Upvotes: 1
Views: 250
Reputation: 53874
You need to re-evaluate useContext
on state.users
change:
const userContext = React.useMemo(
() => ({
//...
userNumbers: state.users,
}),
[state.users]
);
Upvotes: 1
Reputation: 281636
You need to re-create the userContext value
when state.users
change by adding state.users
as a dependency to useMemo otherwise you context value will keep holding the same reference of value and will note trigger change for any listeners
const userContext = React.useMemo(
() => ({
addUsers: data => {
dispatch({
type: 'ADD_USER',
newUsers: data.newUsers
});
},
userNumbers: state.users
}),
[state.users] // Add a dependency here so that user update changes reference
);
Also you should define your reducer to be pure, i.e it shouldn't use state from closure
const [state, dispatch] = React.useReducer((prevState, action) => {
switch (action.type) {
case 'ADD_USER':
return {
...prevState,
users: prevState.users + action.newUsers // use prevState here
};
}
}, {
users: 0
});
P.S. You need not define addUsers
function to be async
. dispatch
happens asynchronously but requires a re-render to take effect and you need not wait on it
Upvotes: 1