How to prevent unwanted re-renders to stop another API call in react js?

  javascript, reactjs

Here is a parent component (Cart) and a child component (CartItem).

in the parent, there is a button that counts on the state that changes by the checkAvailability function which passed to the child via props,

import {useState} from "react";
import CartItem from "./CartItem";

const Cart = ({cart}) => {
    const [available, setAvailable] = useState(true);

    const checkAvailability = (check) => {
        setAvailable(check)
    }


    return (
        <>
          {cart.items.map((item) => (
              item.is_valid && 

                  <CartItem 
                      key={item.id}
                      checkAvailability={checkAvailability}
                  />
          ))}


          <button disabled={available} >Click Me!</button>
        </>
    )
}

export default Cart;

in the child component, an API call returns true or false called by useEffect.

import {useEffect} from "react";


const CartItem = ({checkAvailability}) => {


    const handleCheck = async () => {
    
       const data = await api.call();
       
       if(data.available === false) {
        checkAvailability(false)
       } else if(data.available === true) {
        checkAvailability(true)
       }
    };

    useEffect(() => {
        handleCheck();
    }, []);



    
    return (
        <div> Item </div>
    )
};

export default CartItem;

issue:

every time the components mount, the API call in the child returns a value, that value gets passed to the parent by the checkAvailability function as a prop, which changes the state in the parent, when the state changes a re-render happen which restarts the circle infinitely.

what is the solution?.

Source: Ask Javascript Questions

LEAVE A COMMENT