Skip to content
This repository has been archived by the owner on Dec 29, 2022. It is now read-only.

Latest commit

 

History

History
113 lines (92 loc) · 3.78 KB

GettingStarted.stories.mdx

File metadata and controls

113 lines (92 loc) · 3.78 KB

import { Meta } from '@storybook/addon-docs/blocks'; import { useDarkMode, DarkModeProvider } from '../hooks/useDarkMode'; import { ThemeText, ToggleButton } from './ToggleExample'; import { Text } from 'react-native';

rex-state-logo

Rex State

Convert hooks into shared states between react components

Build Status Maintainability Test Coverage

Version Downloads Bundlephobia

Star on GitHub Watch on GitHub Twitter Follow

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>
    </>
  );
};

Working Example