Replies: 3 comments 1 reply
-
|
In that case the simplest approach is to sync the observables to state, e.g. function useMyHook(store) {
const [val, setVal] = useState(() => store.observable)
useEffect(() => reaction(() => store.observable, v => setVal(v)), [])
// something with val
}As you can see that can easily be turned into it's own generic utility hook as well. |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Another more natural way is to let the component observe and pass observed value(s) as param(s) to the custom
export const MySuperComponent: React.FunctionComponent = observer(() => {
const { myObservedValue } = myStore
const result = useMyHook(myObservedValue)
return <>Whatever the view is<>
}
export const useMyHook(myObservedValue) {
// ...
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
I think this works.... so far so good. example const count = useMobxSelector(() => myMobxStore.count);// useMobxSelector.ts
import {comparer, type IReactionOptions, reaction, toJS} from 'mobx';
import {useEffect, useState} from 'react';
export function useMobxSelector<T>(
selector: () => T,
options?: IReactionOptions<T, false>,
): T {
const [value, setValue] = useState(() => toJS(selector()));
// biome-ignore lint/correctness/useExhaustiveDependencies: selector/options close over stable store refs; re-subscribing on every render would be wrong
useEffect(() => {
const dispose = reaction(
() => toJS(selector()),
(plainValue) => setValue(plainValue as T),
{
fireImmediately: true,
equals: comparer.structural,
...options,
},
);
return dispose;
}, []);
return value;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Wrapping React components with
observerseems to be required when interacting with observable values from MobX store.However, when I have most of my logic/utility written in a custom hook which requires some values from the store, the component that calls the hook must also be wrapped with
observer. This is not very friendly, as there's no way to tell which of my custom hooks require the caller to be wrapped withobserver.Is there a recommended guideline on this?
Beta Was this translation helpful? Give feedback.
All reactions