1

In my project, I create a custom react hook that needs to use observable state in store for dependencies of useEffect:

My example custom hook:

const useFoo = (() => {
   const { count } = store;
   useEffect (() => {
      //do something here   
   },[count])
})

Normally we must wrap observer() the component to make it rerender but observer() does not accept wrap custom hook. I have already referred to another question in this question but this isn't clearly answered to me.

So Anyone can give me a solution to do this. I realize custom hook should be isolated from data to be reusable but in my case, I will save a lot of time to refactor code if I have solution for this problem. Thanks a lot

HauLuu
  • 19
  • 2

1 Answers1

1

The observable data you dereference in useFoo will be picked up by the observer components that use it, so your observer components using useFoo will re-render as expected.

Example

const { useEffect } = React;
const { observable } = mobx;
const { observer } = mobxReact;

const store = observable({
  count: 0,
  increment() {
    store.count++;
  }
});

const useFoo = () => {
  const { count } = store;

  useEffect(() => {
    console.log(count);
  }, [count]);
};

const App = observer(() => {
  useFoo();

  return <button onClick={store.increment}>Click me</button>;
});

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobx/6.4.2/mobx.umd.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobx-react-lite/3.3.0/mobxreactlite.umd.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobx-react/7.3.0/mobxreact.umd.production.min.js"></script>

<div id="root"></div>
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • 1
    Because I think component can't trigger rerender when I don't wrap with observer so I haven't tried this solution u give to me before. Now, it's work. Thank u a lot. – HauLuu Mar 16 '22 at 03:16
  • @HauLuu Great! If you think it answers your question you can [accept it](https://meta.stackexchange.com/a/86979). – Tholle Mar 16 '22 at 08:09