Skip to content

Could you provide an example of how to use this library with react while initializing state with props? #336

Closed Answered by dai-shi
nratter asked this question in Q&A

You must be logged in to vote

If a proxy state is defined at module level, it's already initialized, so you should basically change it with useEffect.

const state = proxy({ text: 'hello' })

const Component = ({ initialText }) => {
  useEffect(() => {
    state.text = initialText
  }, [])
  // ...
}

If this is not something you are looking for, a possible pattern is lazy initialization in render (which requires deeper understanding), or use context: https://github.com/pmndrs/valtio/wiki/How-to-use-with-context

Replies: 1 comment

You must be logged in to vote
0 replies
Answer selected by nratter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #334 on January 24, 2022 00:47.