Why do I need to wrap my react components with observer when using React's useState or useMemo? #3570
-
const TimerView = observer(() => {
const [timer] = useState(() => new Timer()) // See the Timer definition above.
return <span>Seconds passed: {timer.secondsPassed}</span>
}) In the above code, even without wrapping the component with observer, my TimerView is being updated in response, which is based on how react state updates. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you remove observer the component stops updating (unless parent component is updating, which trigger the update for children). |
Beta Was this translation helpful? Give feedback.
If you remove observer the component stops updating (unless parent component is updating, which trigger the update for children).
useState
is used here only to keep value between component rerenders. The value that holdsuseState
is never updated. Notice that you haveconst [timer] = useState(...)
, notconst [timer, setState] = useState(...)
. Only Mobx is involved here to update the component