I'm trying to build an app with react native and react navigation, such that changing something in one screen will also change it in the other.
So far, the only way I have found to be able to sync data between the two screens, is to use buttons with onPress={() => navigate('OtherScreen', this.state)}
. This has two problems. Firstly that it only works where I explicitly call navigate - when I swipe to change screen, it won't transfer the data. But mostly, this just seems contrary to the react philosophy, that data should be pulled from the model by the render call, rather than one render method pushing data into another component.
This has completely stumped me. My current "solution" is to write my entire app in a single file, so that everything is in the same scope and I can use a global variable to store the global state.
I cannot possible be the first person to have this problem, and I find it hard to imagine that react-native would not have any built-in method for defining an application-wide data store.
Is there a standard pattern for sharing data globally in react-native?
How can I sync data between two screens?
In a small app, React Context along with useState is the best way to share state or simply pass data around components without mutating it. Context: It provides a way to share values between components without having to explicitly pass a prop through every level of the tree.
Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props.
To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.
You can use Context or Redux to share between containers(screens) or components.
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
Redux is a predictable state container for JavaScript apps.
There two kinds of sharing states.
onPress={() => navigate('OtherScreen', this.state)}
redux
/ react-redux
).When using redux-cli with navigation, be sure that all routes are inside the <Provider>
, so you can call it globally.
return (
<NavigationContainer>
<Provider store={store}>
<LoadingActivity />
<Routes />
</Provider>
</NavigationContainer>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With