DEV Community

Jefferson Osagie Iyobosa
Jefferson Osagie Iyobosa

Posted on • Edited on

React useEffect hook delays before updating after dispatch

I'm currently working on a side project, an app like unsplash.com

I have been able to get most of the features done, however I'm not satisfied with the performance I get when opening an image in a modal window for larger view.

This issue starts when I have mapped through a large array of data, thereby creating numerous photo component-

//Components

//For holding the image and the actions related to it
//It has an event listener to dispatch the current photo ID to State
<PhotoComponent payload={...}/>

//For creating a dialogue overlay for showing currently viewed image
<Modal />

//The component for loading the currently viewing image
//Has a useEffect() to listen to state so it renders the current image ID in state
<View payload={...}/>

//Liking the photo
<Like />

//Adding photo to collection
<Collect />

So basically all these components are wrapped inside the PhotoComponent. And when I map through the photos array-

const photos = [...] //Where length is over 100
photos.map(p=> <PhotoComponent payload={p} />)

And click on an image, it is supposed to dispatch to state the clicked image ID so that I retrieve that ID in state.
However this event is dispatched and state updated with the image ID.

However, the useEffect() hook takes time (about 2-3sec depending on how much the photos are) to update the with the value from state.

This is really impacting on the app and making it slow to render. I am learning React and I can't think of a better way to solve this.

I'm sorry if I'm not being descriptive enough.

Summary is:

  1. Click on a photo
  2. Dispatch an action to update state with the photo's ID
  3. Opens up a modal to load the image whose iD was dispatched in 1 above

The problem is the modal component delays before it is updated with the item in state (useEffect())

And if the photos are over 200, it takes even more time to effect.

My observation is, it seems there is a loop running through all the images before the update is done.

I need help please, can't seem to figure this out. Thanks

Top comments (0)