https://github.com/icorbrey/react-context-stateful
A simple wrapper that makes it easy to create simple, stateful contexts.
https://github.com/icorbrey/react-context-stateful
react react-context react-wrapper showcase stateful
Last synced: 3 months ago
JSON representation
A simple wrapper that makes it easy to create simple, stateful contexts.
- Host: GitHub
- URL: https://github.com/icorbrey/react-context-stateful
- Owner: icorbrey
- License: mit
- Created: 2020-07-10T19:43:04.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-10-12T20:44:45.000Z (over 5 years ago)
- Last Synced: 2025-02-25T14:13:57.273Z (11 months ago)
- Topics: react, react-context, react-wrapper, showcase, stateful
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/react-context-stateful
- Size: 17.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# react-context-stateful
A simple wrapper that makes it easy to create simple, stateful contexts.
## Install
```sh
# Using NPM
npm install react-context-stateful
# Using Yarn
yarn add react-context-stateful
```
## Usage
To create a stateful context, pass `createStatefulContext()` a functional
component and export its results:
```js
// TodoContext.jsx
import createStatefulContext from 'react-context-stateful'
export [
useTodo,
TodoProvider
] = createStatefulContext(Provider => ({ children }) =>
{
const [todoList, setTodoList] = useState([])
const addTodoItem = item =>
{
// ...
}
const popTodoItem = () =>
{
// ...
}
return (
{ children }
)
})
```
The `Provider` component can then be used at the project root:
```js
// index.js
import { TodoProvider } from './TodoContext'
ReactDOM.render(
,
document.getElementById('root')
)
```
The `Context` object is then available to use in hooks:
```js
// TodoAdder.jsx
const TodoAdder = () =>
{
const { addTodoItem } = useTodo()
// ...
}
export default TodoAdder
```
This package also includes support for defining your contexts with TypeScript:
```ts
import createStatefulContext from 'react-context-stateful'
type TodoState = {
popTodoItem: () => string
addTodoItem: (item: string) => void
}
export [
useTodo,
TodoProvider
] = createStatefulContext(Provider => ({ children }) =>
{
const [todoList, setTodoList] = useState([])
const addTodoItem = (item: string) =>
{
// ...
}
const popTodoItem = (): string =>
{
// ...
}
return (
{ children }
)
})
```