-
Given a simple component:
This does not trigger. What is the best way to react to props changes? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
https://mobx.js.org/react-integration.html#computed-props Either use effect to move props to local observables and another effect with reaction accessing only observables.
This was only possible with classes and we're actually about to remove this feature.
Yes, ideally try to avoid that. |
Beta Was this translation helpful? Give feedback.
-
I came up with a simple solution: a hook that wraps the props as an observable. Not sure if this approach has any downsides - if you use const useObservableProps = <T extends object>(props: T) => {
const store = useLocalObservable(() => props);
useEffect(
action(() => {
Object.assign(store, props);
}),
[props]
);
return store;
};
const TestComponent = observer((props: { text1: string; text2: string }) => {
const observableProps = useObservableProps(props);
useEffect(() => autorun(() => console.log("Text 1", observableProps.text1)), []);
useEffect(() => autorun(() => console.log("Text 2", observableProps.text2)), []);
console.log("Render TestComponent");
return (
<div>
{props.text1} {props.text2}
</div>
);
}); The example is just for illustration, it only makes sense to use this if you combine local state with global state. |
Beta Was this translation helpful? Give feedback.
https://mobx.js.org/react-integration.html#computed-props
Either use effect to move props to local observables and another effect with reaction accessing only observables.
Or unwrap observables to immutable primitives and pass them as deps to normal
useEffect
without reaction.Or don't do it reactively and move the effect to an action that caused the props to update.
This was only possible with classes and we're actually about to remove this feature.
Yes, ideally try to avoid that.