diegohaz / constate

React Context + State

Home Page:https://codesandbox.io/s/github/diegohaz/constate/tree/master/examples/counter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to pass props between nested providers

CoinCoderBuffalo opened this issue · comments

commented

Looking for guidance on how to pass props between two constate hooks.

I need to pass the value for "theme", which will be "dark" or "light", to the useColorsContext hook.

import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import { Text } from 'react-native-paper';
import { ThemeProvider, useThemeContext } from '../hooks/useTheme';
import { ColorsProvider, useColorsContext } from '../hooks/useColors';

function TestComponent(props) {
	
	const { theme } = useThemeContext();
	const { colors } = useColorsContext( -->> PASS THEME VALUE <<-- );
	
	return (
		<View>
			<Text>testing</Text>
		</View>
	);
}

export default function Test(props){
	return (
		<ThemeProvider>
			<ColorsProvider>
				<TestComponent {...props} />
			</ColorsProvider>
		</ThemeProvider>
	);
}
commented

Hello! This is not specific to Constate. You can do it in many ways. Here are some:

Use theme context inside useColors.

function useColors() {
  const { theme } = useThemeContext();
  ...
}

Use theme context within the constate function.

const [ColorsProvider, useColorsContext] = constate(() => {
  const { theme } = useThemeContext();
  return useColors(theme);
});

Pass value through the Provider.

function useColors({ theme }) {
  ...
}

const [ColorsProvider, useColorsContext] = constate(useColors);

function ThemeColorsProvider(props) {
  const { theme } = useThemeContext();
  return <ColorsProvider theme={theme} {...props} />;
}

function App() {
  return (
    <ThemeProvider>
      <ThemeColorsProvider>
        ...
      </ThemeColorsProvider>
    </ThemeProvider>
  );
}