theKashey / useReselect

hooks friendly reselect

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useReselect

DEVELOPMENT PREVIEW

This is a fork of reselect, mixed with kashe and React hooks.

Idea

Make reselect more hooks compatible by providing automatic per-instance memoization. To achive this memoized value would not be stored just inside createSelector, but also inside per-instance WeakMap with selector used a key.

API

API is 100% compatible with Reselect.

  • createSelector - as seen in reselect

Hooks

useReselect

  • useReselect(cb) - selection runner. All selectors inside would be executed inside a sandbox, making result instance bound.
const getUser = createSelector((state: any, userId: string) => (
  state.users[userId] + `:${recomputations++}`
), i => i);

const User = ({userId, tick}) => {
  const userName = useReselect(() => getUser(state, userId));
  return <span>user({userId}): {userName}</span>
}

// this would work
<>
 <User userId="user1" />
 <User userId="user2" /> 
</>


// this would not, getUser still could hold only one result
const DoubleUser = ({userId, tick}) => {
  const [u1, u2] = useReselect(() => [getUser(state, 'a'),getUser(state, 'b')]);
  return <span>{u1} - {u2}</span>
}

useReReselect

  • useReReselect(cb) - selection runner. Every selector inside would be executed in a personal sandbox, making it instance bound
// every selector would be executed in a personal sandbox
const DoubleUser = ({userId, tick}) => {
  const [u1, u2] = useReReselect(() => [getUser(state, 'a'),getUser(state, 'b')]);
  return <span>{u1} - {u2}</span>
}

Running selectors without React

// run it once
const [u1, u2] = useReReselect(() => [getUser(state, 'a'),getUser(state, 'b')]);
// get "hooks"
const stack = useReReselect.getStack();

// run it with "custom hooks"
const [u1, u2] = useReReselect(() => [getUser(state, 'a'),getUser(state, 'b')], stack);

Sharing results

All selectors are double memoized, letting shareable data be shared.

License

MIT

About

hooks friendly reselect


Languages

Language:TypeScript 66.9%Language:JavaScript 31.3%Language:HTML 1.8%