Custom Context API Integration in React Native

Custom Context API Integration in React Native

React Context API is a way to manage an App state globally. It can be used together with the useState hook to share state between deeply nested components more easily than with useState alone. It was also introduced to solve the problem of passing down props from one component to another (props drilling).

React native

Example of Custom Context API Integration in React Native:

Create the Counter Context

// context/CounterContext.js

import React, { createContext, useState } from 'react';
export const CounterContext = createContext();

export const CounterProvider = ({ children }) => {
  const [count, setCount] = useState(0);
  const increment = () => setCount(prev => prev + 1);
  const reset = () => setCount(0);
  return (
    <CounterContext.Provider value={{ count, increment, reset }}>
      {children}
    </CounterContext.Provider>
  );
};

Wrap Your App with the Provider

// App.js

import React from 'react';
import { CounterProvider } from './context/CounterContext';
import HomeScreen from './screens/HomeScreen';
export default function App() {
  return (
    <CounterProvider>
      <HomeScreen />
    </CounterProvider>
  );
}

Use the Counter in a Screen or Component

// screens/HomeScreen.js

import React, { useContext } from 'react';
import { View, Text, Button } from 'react-native';
import { CounterContext } from '../context/CounterContext';
const HomeScreen = () => {
  const { count, increment, reset } = useContext(CounterContext);
  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 24 }}>Count: {count}</Text>
      <Button title="Increment" onPress={increment} />
      <Button title="Reset" onPress={reset} color="red" />
    </View>
  );
};
export default HomeScreen;

Conclusion:

The React Context API is a powerful tool that, when used correctly, simplifies state management in your React Native app.

React native

Happy Coding!

Previous Article

Magento 2: How to Add Custom Column at Admin Order View Item Orders

Next Article

How to Make Purchase Order Number Field Optional in Magento 2?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨