Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
using state from a context provider within my useEffect dependency array causes an infinite loop

I am using the shopify-buy SDK, which allows me to retrieve the current cart of the user. I am trying to store that cart in my CartProvider which is then used in my Cart component. The problem is when I retrieve information from the cart it's acting a little slow so my component needs to be updated when the state changes, currently I have the following in my getShopifyCart function which is located in my CartProvider.

const [cartItems, setCartItems] = useState([])

const getShopifyCart = () => {
    return client.checkout
      .fetch(currentVendor.cartId)
      .then((res) => {
        const lineItemsData = res.lineItems.map((item) => {
          return {
            title: item.title,
            quantity: item.quantity,
          }
        })
        setCartItems(lineItemsData)
        setLoading(false)
      })
      .catch((err) => console.log(err))
  }

In my Cart component I have the following useEffect.

useEffect(() => {
    getShopifyCart()
  }, [cartItems])

But this causes an infinite loop, even though the cartItems state isn't changing.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are setting the state cartItems inside getShopifyCart which you are calling inside a useEffect which has cartItems as a dependency. Even though the content of the data has not changed, you are creating a new object, hence its hash has changed as well which causes the useEffect to be called again.

If you want to initially fetch the data and set the state, then you need to pass an empty dependency array.

useEffect(() => {
   getShopifyCart()
}, [])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!