0

in react native i have the following files:

App.js

import { StyleSheet, Text, View } from 'react-native';
import Children from './Child';
import { MyProvider } from './context/Context';
import React from 'react';

const App = () => {
  return (
    <MyProvider>
      <View style={styles.container}>
        <Children />
        <StatusBar style="auto" />
      </View>
    </MyProvider>
  );
};

export default App;

Child.js

import React from 'react';
import { View, Text, Button } from 'react-native';
import { useMain } from './context/Context';

const Child = () => {
  const { dummy, setDummy } = useMain();
  const onPressLearnMore = () => {
    setDummy('c');
  };
  return (
    <View>
      <Text>This children {dummy}</Text>
      <Button onPress={onPressLearnMore} title="click" />
    </View>
  );
};

export default Child;

Context.js

import React, { useContext, useEffect, useState } from 'react';
export const mainContext = React.createContext();

export function useMain() {
  return useContext(mainContext);
}
export function MyProvider({ children }) {
  const [dummy, setDummy] = useState('a');
  useEffect(() => {
    setDummy('b');
  }, []);
  function doNull() {
    console.log('do null');
  }
  const value = {
    dummy,
    setDummy,
  };
  return <mainContext.Provider value={value}>{children}</mainContext.Provider>;
}

Everything works as expected, Children component can access { dummy } and { setDummy }, so that i can place all my "shared" functions, states and so on in Context to be used from everywhere. I was just wondering if i can access them in App.js too without coding another component; it looks if i import

import { useMain } from './context/Context';

and then i add this

const { dummy, setDummy } = useMain();

to my App, it does not work, so i'm thinking i can only access things from context only in child, but the first View is a child too!

Should i create a new component if i need access to Context or can it be accessed from the MyProvider level too?

popeating
  • 386
  • 1
  • 2
  • 16

1 Answers1

1

The first view is a child of your provider indeed but App is not, so yes you would need to extract your view as a separate component if you want to access your context from it.

import { StyleSheet, Text, View } from 'react-native';
import Children from './Child';
import { MyProvider, useMain } from './context/Context';
import React from 'react';

const Container = () => {
  const { dummy, setDummy } = useMain();

  return (
    <View style={styles.container}>
      <Children />
      <StatusBar style="auto" />
    </View>
  )
}

const App = () => {
  return (
    <MyProvider>
      <Container />
    </MyProvider>
  );
};

export default App;
Valentin Briand
  • 3,163
  • 2
  • 8
  • 17