Skip to content

Guidance of how to use useEffect to react on state changes #322

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

You must be logged in to vote

Yeah, you are hitting the difficult part of proxy state.
The last option is actually preferable and less error-prone.

If you want to use useEffect deps, the recommendation is to extract primitive values from snapshot in render, and pass them:

  const snap = useSnapshot(state)
  const { num, string, bool } = snap.watchObj
  useEffect(() => {
    ...
  }, [num, string, bool])

This also applies to useMemo and useCallback deps, and also memo.
We should add notes in https://github.com/pmndrs/valtio/wiki/Some-gotchas.

Replies: 2 comments 13 replies

Comment options

You must be logged in to vote
4 replies
@saendu
Comment options

@dai-shi
Comment options

@saendu
Comment options

@dai-shi
Comment options

Answer selected by saendu
Comment options

You must be logged in to vote
9 replies
@webcodion
Comment options

@dai-shi
Comment options

@dai-shi
Comment options

@webcodion
Comment options

@dai-shi
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