https://github.com/mucsi96/react-create-shared-state
useState but with shared state across components
https://github.com/mucsi96/react-create-shared-state
hook react shared usestate
Last synced: 3 months ago
JSON representation
useState but with shared state across components
- Host: GitHub
- URL: https://github.com/mucsi96/react-create-shared-state
- Owner: mucsi96
- License: mit
- Created: 2019-11-07T21:23:28.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2021-05-11T07:08:05.000Z (about 4 years ago)
- Last Synced: 2025-03-18T17:06:20.175Z (3 months ago)
- Topics: hook, react, shared, usestate
- Language: TypeScript
- Size: 569 KB
- Stars: 8
- Watchers: 2
- Forks: 1
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-create-shared-state
[](https://badge.fury.io/js/react-create-shared-state)
[](https://github.com/mucsi96/react-create-shared-state/actions?query=workflow%3ABuild+branch%3Amaster)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.
## Side-by-side comparison with Context API

## Usage
[Demo](https://codesandbox.io/s/react-create-shared-state-demo-9s9ui)
```jsx
import { createSharedState } from 'react-create-shared-state';const useTheme = createSharedState('light');
function App {
return (
);
}function Toolbar() {
return (
);
}function ThemedButton() {
const [theme] = useTheme();
return ;
}function ThemeSwitch {
const [theme, setTheme] = useTheme();
return (
setTheme(theme === 'dark' ? 'light' : 'dark')}
>
{theme}
);
}
```