useStoreMap

React hook, which subscribes to store and transforms its value with given function. Component will update only when selector function result will change

Common use case: subscribe to changes in selected part of store only

useStoreMap({store, keys, fn})

Arguments

  1. params (Object): Configuration object
    • store: Source store
    • keys (Array): This argument will be passed to React.useMemo to avoid unnecessary updates
    • fn ((store, keys) => result): Selector function to receive part of source store

Returns

(State)

Example

This hook is very useful for working with lists, especially with large ones.

import {createStore} from 'effector'
import {useStore, useStoreMap} from 'effector-react'
const data = [
{
id: 1,
name: 'Yung',
},
{
id: 2,
name: 'Lean',
},
{
id: 3,
name: 'Kyoto',
},
{
id: 4,
name: 'Sesh',
},
]
const $users = createStore(data)
const $ids = createStore(data.map(({id}) => id))
const User = ({id}) => {
const user = useStoreMap({
store: $users,
keys: [id],
fn: (users, [userId]) => users.find(({id}) => id === userId),
})
return (
<div>
<strong>[{user.id}]</strong> {user.name}
</div>
)
}
const UserList = () => {
const ids = useStore($ids)
return ids.map(id => <User key={id} id={id} />)
}

Try it

Last updated on