2

Problem

Functional component causes multiple re-renders causing multiple ajax requests. What is the solution for this?

This is my code.

export default function MyMenu() {
    let menu = useStoreState(state => state.menu.menu);
    const getMenu = useStoreActions(actions => actions.menu.getMenu);
    let categoryId = useStoreState(state => state);
    const setCategoryId = useStoreActions(actions => actions.menu.setCategoryId);
    const [localCategoryId, setLocalCategoryId] = React.useState(0);
    React.useEffect(() => {
        getMenu();
    });
    // below is usual return method
}
Farman Ali
  • 97
  • 10

2 Answers2

2

You should pass an array of dependencies as a second argument to useEffect. If you want it run only once - pass an empty array, like this:

 React.useEffect(() => {
    getMenu();
}, []);
Vlad
  • 459
  • 4
  • 8
  • Thanks. There is one more thing to it. I want to run it every time the state changes. – Farman Ali Jan 29 '21 at 12:44
  • So insert your dependency in array, for example if you want to call it every time `menu` changes - `[menu]` – Vlad Jan 29 '21 at 12:46
2

Missing second argument [], look at it:

React.useEffect(() => {
    getMenu();
}, []);
Artur Carvalho
  • 6,901
  • 10
  • 76
  • 105