hookmuts
v1.0.6
Published
React Store - hookmuts . Say useReducer No!
Downloads
16
Readme
hookmuts - React Store
Say: useReducer NO!
Install
npm install hookmuts
Usage
This store was developed for build optimization and ease of use, using both SSR and CSR
First create a store
Init Store:
import createStore from "hookmuts";
interface IInitialState {
count: number,
post: {
id: number,
name: string,
description: {
title: string,
subtitle: string
}
}
}
export const {Provider, useSelector, useDispatch} = createStore<IInitialState>({
initialState: {
count: 0,
post: {
id: 0,
name: 'first',
description: {
title: "Test post",
subtitle: 'about post'
}
}
}
})
Then init Provider in your app. You can use initialValues in
<Provider initialValues={{user: userFromServer}}>
<App/>
</Provider>
to init server constants
And you have useSelector
hook by select state:
const [count, post] = useSelector((state) => [state.count, state.post])
And useDispatch
- dispatch mutation to store
export const usePrevCount = () => useDispatch((state) => {
return {
count: state.count - 1,
}
})
export const useNextCount = () => useDispatch((state) => ({count: state.count + 1}))
export const useSetCount = () => useDispatch((state, payload) => ({count: payload}))
export const useSetSubtitle = () => useDispatch((state, payload) => {
return {
post: {
...state.post,
description: {
...state.post.description,
subtitle: payload
}
}
}
})
In Components :
function App() {
const [count, post] = useSelector((state) => [state.count, state.post])
const prevCount = usePrevCount()
const nextCount = useNextCount()
const setSubtitle = useSetSubtitle()
return (
<div className="App">
<h1>App</h1>
<p>{`Count: ${count}`}</p>
<button type="button" onClick={() => {
prevCount()
}}>
Prev
</button>
<button type="button" onClick={() => {
nextCount()
}}>
Next
</button>
<h2>{`Post : ${post.name}`}</h2>
<p>{post.description.title}</p>
<p>{post.description.subtitle}</p>
<input type="text" value={post.description.subtitle}
onChange={(e) => setSubtitle(e.target.value)}
/>
</div>
);
}
Modules
So, you can create many modules :
import createStore from "hookmuts";
export const {Provider, useSelector, useDispatch} = createStore({
initialState: {
count: 0,
post: {
id: 0,
name: 'first',
description: {
title: "Test post",
subtitle: 'about post'
}
}
}
})
export const {Provider: AuthProvider, useSelector: useAuthSelector, useDispatch: useAuthDispatch} = createStore({
initialState: {
sessionToken: '',
user: {
id: 0,
name: 'Igor',
email: '[email protected]',
image: 'https://example.com'
}
}
})
And use init Providers:
<Provider>
<AuthProvider initialValues={{sessionToken: sessionTokenFromServerCookie, user: userFromServerCookie}}>
<App/>
</AuthProvider>
</Provider>
Happy coding!
License
MIT © Igor Lialko