Farman Ali
Farman Ali

Reputation: 107

useEffect() cause re-renders and multiple requests to api

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
}

Upvotes: 2

Views: 1342

Answers (2)

Artur Carvalho
Artur Carvalho

Reputation: 7167

Missing second argument [], look at it:

React.useEffect(() => {
    getMenu();
}, []);

Upvotes: 2

Vlad
Vlad

Reputation: 477

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();
}, []);

Upvotes: 2

Related Questions