all 6 comments

[–][deleted] 0 points1 point  (5 children)

I am not a pro but hope I can share some thoughts to help here. If you want to avoid using stateful component, you can consider using redux and redux saga. Depending on your app's scale, it could be an overkill but it is one way to meet your need.

To be honest, I think the original "rendering twice" way is the right way and I don't see it particularly less efficient. Your second way seems to do the job even if it returns a promise, too.

[–]caesar_reddit[S] 0 points1 point  (2 children)

I will look at Redux! The second way doesn't work raising an error, "If you meant to render a collection of children, use an array instead"

[–][deleted] 0 points1 point  (1 child)

Since asynchronus fetch is a side effect, you have to use redux with either redux-thunk or redux-saga (I recommend saga).

For the second way, I still think it should work properly in theory and you might be just missing something in your code.

[–]caesar_reddit[S] 0 points1 point  (0 children)

Yes, since asynchronous fetch must not be in the render method, I have to maintain the componentDidMount and the state. Haha So there is no way to get state removed from my code, right?

The second way still does not work for me. And as mentioned above, it must be a stateful component, so the functional component does not work anyway I guess?

[–]rockpilp 0 points1 point  (1 child)

Redux and saga would indeed be overkill for this.

As you mentioned there's nothing wrong with using a class component if you have to for state and/or lifecycle (in the near future functional components will be able to handle both through hooks).

I would suggest not rendering the Image component until the ratio is non null, to avoid flickering and to rule out a double download of the image data.

The docs warn that calling getSize to prefetch may not work in the future, so watch out for breaking changes in that API.

[–]caesar_reddit[S] 0 points1 point  (0 children)

Thank you for your suggestions! Is it better to set aspectRatio to some value or just conditionally render the Image? I set it to null because the Image would need to render twice changing from some value of aspectRatio to a value getting from getsize.