K
K
Kirill2021-01-30 03:09:48
React
Kirill, 2021-01-30 03:09:48

Why doesn't useEffect fire on page reload?

There is a custom hook that listens to the resize and changes the state. If you resize the window, then the blocks change and everything is ok. But if you first change the screen width and then reload the page, the function will not work and the desired block will not be rendered until the resize occurs.

Hence 2 questions:
1. Why is this happening?
2. How to make it so that when the page is reloaded, the screen width is determined and the corresponding state is set?

Thank you.

https://codesandbox.io/s/reverent-gareth-wqn1z?fil...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2021-01-30
@Lirrr

You have two mistakes
. The first is that you add a handler inside the effect and that's it. The handler will be called and will only change the value on resize.
The second is that the useEffect rule about dependencies is violated, isMobile closes.
Look at the finished solution, compare with your own, read the article about useEffect
Ready solution
Article

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question