Skip to content

The right way to set up computed/derived data in the store #161

Closed Answered by dai-shi
ivan416 asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks for opening this up. There are pros/cons, and can't recommend "one" way.

state function to get state (computed) value

const state = proxy({
  count: 1,
  doubled: () => state.count * 2
})

This code alone is valid and state.dobuled() works just fine.
However, there's a pitfall when using with useSnapshot:

const Component = () => {
  const { doubled } = useSnapshot(state)
  return <div>{doubled()}</div>
}

This is not reactive because doubled is reading a mutable state object. So, even if count changes, this component won't re-render.

state function with this that works with snapshot

To do it correctly, here's the solution.

const state = proxy({
  count: 1,
  doubled() { return this.c…

Replies: 2 comments 16 replies

Comment options

You must be logged in to vote
9 replies
@dai-shi
Comment options

@ivan416
Comment options

@dai-shi
Comment options

@ivan416
Comment options

@GorvGoyl
Comment options

Answer selected by ivan416
Comment options

You must be logged in to vote
7 replies
@dai-shi
Comment options

@dai-shi
Comment options

@ndrean
Comment options

@dai-shi
Comment options

@barelyhuman
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants