Home > Software design >  What is the best way in React Native to store global app data used in many screens?
What is the best way in React Native to store global app data used in many screens?

Time:12-04

I am making a React Native app and I need the user data (fetched from firebase database) to be available right after the first screen and in many other screens.

As it is complete user object data, I do not think passing it via the navigator props is suitable. So I am searching for alternatives. Can someone help ?

CodePudding user response:

The best way to store and share global data is Context API or Global Context .

This new API solves one major problem–prop drilling. Prop drilling is the processing of getting data from component A to component Z by passing it through multiple layers of intermediary React components. The component will receive props indirectly . Context provides a way to pass data through the component tree without having to pass props down manually at every level.

To create a context, we use React.createContext which creates a context object. You can pass in anything as an argument to React.createContext.

import React from "react";

const YourContext = React.createContext("value");

To make this context available to all our React components, we have to use a Provider. Every context object comes with a Provider React component that allows consuming components to subscribe to context changes. It is the provider that allows the context to be consumed by other components.

In order to create a provider, we have to import our Context.

  • Related