-
When mix MobX observable with React immutable state/props in useEffect, how to write the dependency list becomes really tricky. useEffect(() => autorun(() => { ... }), [non-observable dependencies]) I think one big problem of this solution is that the effect will not be triggered at the same time if we just use useEffect. I am thinking about another solution: /**
* Just put everything in deps, no matter it is observable or not.
* If it is observable, that means its reference will not change, so changes are tracked by MobX.
* If it is not observable, react will take responsibility to recompute.
*/
const useMobxMemo: typeof useMemo = (factory, deps) => {
return useMemo(
() => computed(factory),
deps
).get()
}
export const useMobxEffect: typeof useEffect = (effect, deps) => {
// use useMobxMemo to generate a new deps
const memorizedDeps = useMobxMemo(() => deps && [...deps], deps)
// put memorizedDeps as the only dependency, if useMobxMemo works correctly,
// the reference of memorizedDeps will only change if the real deps change
return useEffect(effect, memorizedDeps && [memorizedDeps])
} I think this will trigger effect the same way of original useEffect, and works better with lint rules. You just put everything into dependency list. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
How so? If I read it correctly, the observable isn't accessed inside tracking context (render/computed/effect), therefore not tracked. |
Beta Was this translation helpful? Give feedback.
How so? If I read it correctly, the observable isn't accessed inside tracking context (render/computed/effect), therefore not tracked.
Related:
#3224
#3348
#3252