React Native

What is the Context API in React Native and how is it used?

Medium
4
Added
The Context API is a way to pass data through the component tree without having to pass props down manually at every level.

Solution Code

React Native
-- Example Code --
import React, { useState, useContext, createContext } from "react";
import { View, Text, Button } from "react-native";

const MyContext = createContext();

const App = () => {
  const [count, setCount] = useState(0);

  return (
    <MyContext.Provider value={{ count, setCount }}>
      <Counter />
    </MyContext.Provider>
  );
};

const Counter = () => {
  const { count, setCount } = useContext(MyContext);

  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
};

export default App;
Explanation
This code demonstrates how to use the Context API to share state between components.

Guided Hints

{'hint': 'Use createContext to create a context.'}
{'hint': 'Use useContext to consume the context.'}