This package allows sharing data between components with hooks. In many cases leads to more simple implementation compared to Context API.
createSharedState
creates a hook very similar to useState
but with sync state across hook instances. Setting a value in one component will result re-rendering every component which uses the same hook.
import { createSharedState } from 'react-create-shared-state';
const useTheme = createSharedState('light');
function App {
return (
<Toolbar />
<ThemeSwitch />
);
}
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const [theme] = useTheme();
return <Button theme={theme} />;
}
function ThemeSwitch {
const [theme, setTheme] = useTheme();
return (
<Button
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
>
{theme}
</Button>
);
}