Skip to content

React useMemo with observable state #3348

Answered by kykungz
kykungz asked this question in Q&A
Discussion options

You must be logged in to vote

Just found out a solution when tweaking around with the code.

Instead of returning the final value through .get() inside useMemo

// ❌ changes in `store.threshold` will not be reflected
const filtered = useMemo(() => {
  return computed(() => props.list.filter(value => value > store.threshold)).get()
}, [props.list])

Just return the everything as a computed value from useMemo and use .get() afterwards:

// ✅ changes in `props.list` AND `store.threshold` will now be reflected
const filtered = useMemo(() => {
  return computed(() => props.list.filter(value => value > store.threshold))
}, [props.list]).get()

store.threshold will be tracked through computed function, props.list will be tracked …

Replies: 3 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by kykungz
Comment options

You must be logged in to vote
1 reply
@kykungz
Comment options

Comment options

You must be logged in to vote
1 reply
@kykungz
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
3 participants