VOOZH about

URL: https://www.geeksforgeeks.org/react-native/creating-context-in-react-native/

⇱ Creating Context in React Native - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Creating Context in React Native

Last Updated : 19 Jan, 2026

Creating context in React Native allows you to share state and functions across multiple components in a simple and centralized way. It helps avoid passing data through multiple component layers.

  • Uses React’s createContext function to create a shared data store.
  • Allows values to be accessed by any nested component.
  • Eliminates the need for repetitive prop passing (prop drilling).

Implementing Context in React Native

It provides a simple way to share and manage data across multiple components without passing props through every level.

1. Import React:

Begin by importing the necessary modules at the top of your file.

Here, we import the createContext, useState, and useContext functions from React, as well as some basic React Native components.

2. Create a Context:

Use the createContext function to create your context. This function returns an object with Provider and Consumer components.

3. Create a Provider Component:

Now, create a component that will act as the provider for your context. This component will wrap around the parts of your app where you want the shared data to be available

In this example, myData is the shared state, and setMyData is a function to update that state. The Provider component takes a value prop, which is an object containing the shared data.

4. Use the Provider:

Wrap the root of your component tree with the MyProvider component.

Now, any component inside MyProvider can access the shared data using the MyContext.Consumer or the useContext hook.

5. Consume the Context with Class Components:

If you are using class components, you can consume the context using the MyContext.Consumer component.

6. Consume the Context with Functional Components:

If you are using functional components, you can use the useContext hook.

Now, MyComponent can access and modify the shared data without the need for prop drilling.

  • Adjust the example according to your specific use case and data requirements.
  • The structure shown covers the basic steps for creating and using Context in a React Native application.
Comment
Article Tags:

Explore