Skip to content

why using snapshots in callbacks is a bad idea? #290

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

You must be logged in to vote

Thanks for raising this up.
Yeah, the problem is not reading stale value, but it's about state usage tracking.

const state = proxy({ count: 0, text: '' })

function App() {
  const snap = useSnapshot(state)
  const handleClick = () => {
    console.log(snap.text) // This is not recommended as it can cause extra re-renders
  }
  return (
    <div>
      {snap.count} <button onClick={handleClick}>click</button> 
    </div>
  )
}

Once, you click the button, the useSnapshot hook can mistake that text is used in render, which may cause re-render if text changes. snap is really meant to be used only in render function.

Replies: 1 comment 9 replies

Comment options

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

@MD2990
Comment options

@dai-shi
Comment options

@jorroll
Comment options

@dai-shi
Comment options

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