Skip to main content
Version: 1.0.x

useReduxState()

This hook allows to create redux state at runtime.

useReduxState(stateName?: string, state?: any)

or

useReduxState(config?: {
path?: string, // nested state path
state?: any, // initial state
reducer?: (storeState, initialState) => mergedState
})

returns{}#

config#

path''#

type: string default: Date().getTime()
nestable key path of the redux state

useReduxState({ path: 'state.name', state: 'Mike' })
// creates nested state in the store {state: {name: 'Mike'}}

state?#

type: any
initial state

useReduxState({ path: 'state.name', state: 'Mike' })
// creates nested state in the store {state: {name: 'Mike'}}

reducer()?#

type: function
function that takes the current state for the given path, payload and returns computed new state. this function runs once during the initialization of the state use the function when you want to manually handle how the state should be created/updated.

useReduxState({ path: 'state.name', state: { is: 'Mike' } })
// {state: {name: {is: 'Mike'}}}
useReduxState({
path: 'state.name',
state: { and: 'Redux' },
reducer: (currentState, payload) => ({ ...currentState, ...payload })
})

in the above example reducer had prevented from over-writing the store state when there is an existing value for the state. instead of:

{
state: {
name: {
and: 'Redux'
}
}
}

we got:

{state: {name: {is: 'Mike', and: 'Redux'}}}

unmount?#

type: boolean default: false

determines whether redux state should mount

useReduxState({ unmount: true, path: 'state.name', state: 'Mike' })
// store undefined
useReduxState({ unmount: false, path: 'state.name', state: 'Mike' })
// {state: {name: 'Mike'}}

cleanup?#

type: boolean

determines whether redux state should cleanup the state when component unmounted from view.

const { getState } = useReduxState({
cleanup: true,
path: 'state.name',
state: 'Mike'
})
useEffect(() => {
console.log(getState()) // {state: {name: 'Mike'}}
return () => console.log(getState()) // undefined
}, [])

Example#

import React, { useEffect } from 'react'
import { View, StyleSheet, Button, Alert } from 'react-native'
import useReduxState from 'use-redux-states'
const App = () => {
const {
selector,
useMemoSelector,
getState,
cleanup,
setState
} = useReduxState({
/* nestable state path */
path: 'state.name',
/* initial component state */
state: {
count: 1,
locale: 'en_US'
},
/* if state !exists overwrite with payload */
reducer: (state, payload) => state || payload,
/* whether state should be mounted */
unmount: false
})
const { count, locale } = useMemoSelector(selector, (state) => state)
useEffect(() => {
/* delete the state when component unmount from tree */
return () => cleanup()
}, [])
return (
<Button onPress={() => setState({ count: count + 1 })}>
<Text>
{count}, {locale}
</Text>
</Button>
)
}
export default App