immerjs / use-immer

Use immer to drive state with a React hooks
MIT License
4.04k stars 92 forks source link

How to avoid the problem come from `capture value` of function component? #41

Closed qinhuaihe closed 4 years ago

qinhuaihe commented 4 years ago

reproduction

use-immer is really helpful. But I don't know what to do to solve the capture value problem.

Look at the reproduction, when I click the add button, the value changed. But the print method just printed the old value. How to avoid this problem?

mweststrate commented 4 years ago

In react state is only visible after it has been rendered. So if you have side effects that should see the state, you should call using useEffect, .e.g useEffect(() => { print(state.value }, [state.value])

On Tue, Nov 26, 2019 at 6:44 AM zmayor notifications@github.com wrote:

reproduction https://codesandbox.io/s/useimmer-capture-value-541ro

use-immer is really helpful. But I don't know what to do to solve the capture value problem.

Look at the reproduction, when I click the add button, the value changed. But the print method just printed the old value. How to avoid this problem?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/immerjs/use-immer/issues/41?email_source=notifications&email_token=AAN4NBB7MYDCDH6YA7L55RDQVTATBA5CNFSM4JRTIWF2YY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4H4ATWKQ, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAN4NBDCST2EVG6JY3LCOFDQVTATBANCNFSM4JRTIWFQ .