0

I'm using a useEffect as a componentWillMount, but it is behaving unexpectedly.

In Component, (as you can see in the Codesandbox below), the code in useEffect should fire before the return content is hit, but for some reason, the useEffect is entered after the DOM has loaded.

In the below sandbox, I'm loading two images, imgsSrc1 and imgsSrc2. In my useEffect, I'm creating an image DOM element, and setting its src prop to imgsSrc1. In my return, I have an img element that has its src prop set to imgsSrc2.

I would expect imgsSrc1 to start downloading first, but when I look into the network tab of the dev console, I see that imgsSrc2 starts downloading first:

img1

Why is this happening? Is this NextJS behavior?

green-water-gjdhz

Mike K
  • 7,621
  • 14
  • 60
  • 120
  • [`UNSAFE_componentWillMount`](https://reactjs.org/docs/react-component.html#unsafe_componentwillmount) is deprecated (and `useEffect` was never a stand in for it as per the answer below) ...lifecycle overview here: [The Component Lifecycle](https://reactjs.org/docs/react-component.html#the-component-lifecycle) – pilchard Nov 15 '20 at 10:33

1 Answers1

3

useEffect will always behave this way

It is firing after the component is mounted and then you need tell it to render again the component with the new data you got after it runs the code in your useEffect function

From the official website :

" By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. "

useEffect will run after the first render

" Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects."

Hopefully, it's more clear now.

If not, try looking through the documentation

https://reactjs.org/docs/hooks-effect.html

Yosi Leibman
  • 386
  • 3
  • 16
Dolev Dublon
  • 643
  • 1
  • 6
  • 16
  • 1
    So, does this mean I can't create a `componentWillMount` hook? I'd have to implement a [hacky way](https://stackoverflow.com/a/62701724/2891356)? – Mike K Nov 15 '20 at 10:32
  • 1
    The standard use is to conditionally render the first render then update/initialize when useEffect runs then show on second render. – pilchard Nov 15 '20 at 12:07
  • they change the way component did mount works so you can , maybe this will help you more , https://stackoverflow.com/questions/53464595/how-to-use-componentwillmount-in-react-hooks?noredirect=1&lq=1 – Dolev Dublon Nov 15 '20 at 12:15
  • if i answered your question can you mark my answer as the answer >? please ? – Dolev Dublon Nov 15 '20 at 12:16