import { Meta } from '@storybook/addon-docs/blocks'; import { useDarkMode, DarkModeProvider } from '../hooks/useDarkMode'; import { ThemeText, ToggleButton } from './ToggleExample'; import { Text } from 'react-native';
Convert hooks into shared states between react components
Rex State allows you to convert the result of your hooks into a shared state between multiple react components using the Context API.
import { createRexStore } from 'rex-state';
// A simple hook to toggle theme modes between 'light' & 'dark'
const useThemeHook = (initialTheme = 'light') => {
const [theme, setTheme] = useState(initialTheme);
const toggleTheme = () => setTheme(theme === 'light' ? 'dark' : 'light');
return [theme, toggleTheme];
};
// using `createRexStore` to create a Provider & a Hook with shared state
const { useStore: useTheme, RexProvider: ThemeProvider } = createRexStore(
useThemeHook
);
// Use the `ThemeProvider` at the top level of your React component tree
const App = () => {
// `initialTheme` value can be supplied using the value prop of `ThemeProvider`
return (
<ThemeProvider value="dark">
{/* Rest of your application */}
<ToggleButton />
</ThemeProvider>
);
};
// All components can now access the `useTheme` hook
const ToggleButton = () => {
const [theme, toggleTheme] = useTheme();
return (
<View>
<Text>Is Dark Mode?</Text>
<Switch value={theme === 'dark'} onValueChange={toggleTheme} />
</View>
);
};
// Calling `toggleTheme` in above component will cause updates
// in all the components in the Application tree using the context API
const ThemeText = () => {
const [theme] = useTheme();
return (
<>
<Text>Theme Mode: </Text>
<Text>{theme}</Text>
</>
);
};