Skip to content

How to reset state/proxy on component unmount? #199

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

You must be logged in to vote

In this case, I would suggest to reset proxy state explicitly.
https://codesandbox.io/s/currying-cherry-yh5ip

How can I mimic this behaviour with valtio?

Alternatively, you could store the proxy state in useRef to work with react component lifecycle.

export const ValtioLocalStateTest = () => {
  const state = useRef(proxy({ count: 0, userName: "Default userName" })).current
  const snap = useSnapshot(state)

  return (
    <div>
      <h3>Valtio local state test</h3>
      <div>Counter: {snap.count}</div>
      <div>
        <button onClick={() => ++state.count}>Counter +1</button>
      </div>
      <div>Username: {snap.userName}</div>
      <div>
        <input value={snap.userName} o…

Replies: 3 comments 12 replies

Comment options

You must be logged in to vote
2 replies
@epsilon42
Comment options

@dai-shi
Comment options

Answer selected by epsilon42
Comment options

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

@niraj-khatiwada
Comment options

@dai-shi
Comment options

@niraj-khatiwada
Comment options

@dai-shi
Comment options

Comment options

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

@user753
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
5 participants