Search code examples
androidreact-nativereduxstatesetstate

How to access the state of a component form another component in react-native?


I am accessing the location data using the geolocation API and storing it inside the state of a component called Location.js, but I want to access the state from a different independent component say Slider.js. What is the simplest and fastest way to access the state? I am a beginner. Any help will be appreciated. ie, How to make a state "global" in some sense because I have some other components that want to access the state of Location apart from Slider. There are 10 components which would use the location state of Location.js, then I would have to perform a POST operation using the location data and some data from Slider also.

I did some research -

  • Some are suggesting to send the state data via props, but I never use the Slider component inside the Location component. If this can be done, please elaborate.

  • Somewhere I found about redux, how can it be helpful? And how do I decide I really need it? If yes, can anyone explain briefly how?


Solution

  • The question you are asking is not specific to React Native, but it could be asked about a regular web app written with ReactJS (I say this because it is often easier to find tutorials, etc. in the bigger community of ReactJS)

    That being said you have two options:

    1. Since your components are separate, you could consider creating a wrapper component, often called a Higher Order Component (HOC), which will encompass both of those components. You should have the geolocation call present in the HOC component and send it down via props to any child component that needs it.
    2. Use a state management tool - Redux is the most popular state management tool in the React world, but it is not the only one. Another very popular one is MobX. You can think of state management tools like umbrellas that cover your entire application. You can access state stored in Redux in any component, no matter what the parent-child structure is of your application. Redux is considered to have a complex bootstrap, if you do decide to try it out I highly recommend going through this free course on Egghead.io: https://egghead.io/courses/getting-started-with-redux This course was created by Dan Abramov, the actual creator of Redux :)

    I hope this helps ;)