What causes a re-render to happen?
What causes a re-render to happen?
There are three main things which can cause a re-render
I found a cool blog*. This dude bro says: "Every re-render in React starts with a state change. It's the only `trigger` in React for a component to re-render." HMMM. Is that true? MY BRO adds an asterisk. WHY DOES HE ADD AN ASTERISK? Great so this dude bro adds an asterisk and then he doesn't answer his own asterisk. why my bro why
I NEED MORE ANSWERS. I asked my team and they said "Everything." "Mars aligning." Come on my dudes. You can do better than that
I asked chat gpt as I remembered there a three main ones
- State Changes
- Props Changes
- Context value Changes
MY COLLEAGUE CONFIRMS THAT THIS EFFECTIVELY COVERS EVERYTHING
JOB DONE
He shows me a live demo; running loops to create rows in a table and running a loop to create comments in a table. Tables are really dangerous because it's easy to create a loop that really makes the code slow and sluggish.
- useCallback
- useMemo
We talked about those briefly - they're on my plan! Memoisation is a thing. Caching. Directly related to caching. useCallBack is a thing. In React two types of caching
- useCallback
- useMemo
useCallback is caching the function itself. if you have a function that is expensive because it pulls in things and is LONG - I don't want this running hundreds of times - you cache that.
useMemo caching the end RESULT of useCallback
start at surface level with these - delve deeper gradually and later - one caches a function, and the other caches the results of that function.
any time the cached function has to be reused, the whole table component re-renders
useCallback uses a dependency array like useEffect
instead of re-run function -
delete the cache and redo it -
because we pass the function as a prop and react is always looking to see if the props have changed - if the cache remains intact, no re-render is caused because React can see that nothing has changed
Because we've put something in the dependency array
any time the dependency array changes
- you click a button
- that causes the function to get called
- the cache gets thrown out
- the prop which is a function changes - because the cache is gone - so the function getting called again seems like a new prop - and this makes the whole table re-render
- He sent me this structured thing:
"""
Button click
> updates VARIABLE
> FUNCTION's cache is removed and it has to re-run
> the FUNCTION prop to THE COMPONENT changes
> THE COMPONENT re-renders
"""
.png)
Comments
Post a Comment