r/learnreactjs • u/Southern_Builder_312 • Feb 29 '24
Can anyone explain how lazy load works
- If we return some js file instead of jsx what happens
- How does react knows component is returned by lazy
6
Upvotes
1
u/TheWebUiGuy Feb 29 '24
Lazy loading is basically the browser saying its going to load the resources it needs to render straight away first so the page displays fast. Then as other content is needed load it bit by bit to reduce the overall load at any given time
1
u/ferrybig Mar 01 '24
Lazy works by being a function that accepts a callback, which returns a promise, which should contain an object with the key
defaultbeing a React component. One other behavior of this is that is calls the callback only when the component is being rendered the first time, and not before or after that point in time.It is common we pass a function that calls the dynamic import api to load a javascript module as a promise.
Because lazy works with the suspense system and only loads data 1 time, we need some state outside the react world.
A simple implementation of the lazy function is as follow
Lazy is a small component with a single goal, making it quite versatile