Many new features are released in React v16.6.0.
React.memois one of the cool features in it.
memomeans memorizing. This is a performance optimization feature for the function components.
React.memo()is similar to
PureComponentthat it will help us control when our components rerender.
Components will only rerender if its props have changed! Normally all of our React components in our tree will go through a render when changes are made. With PureComponent and React.memo(), we can have only some components render.
memohas made it easier to avoid the continuous rendering process that we could do with the
shouldComponentUpdate()method. A compiled package to prevent unwanted re-rendered operations.
I'll try to explain it with a simple example.
Let's consider it in a simple way. We have a parent component called
Parentthe main logic in it and a child component called
Childsimply console logging and renders some text.
Parent.js, the console will log "Log from Child component." every time you type in the input. It's because every time we set the state with the
onChangefunction, the whole
Parentcomponent re-renders and therefore updates the
Childcomponent. Since the
Childcomponent is static, we do not have to render it every time we set the text state.
To prevent this, we needed to use the
shouldComponentUpdate()method. Now we can overcome this problem with
Here are 2 ways:
If you'd like to memoize the
Childcomponent from components to components, just import it and use
React.memo()inside that component:
If you'd like to globally memoize the Child component, go with the following:
With these methods, we're now preventing unnecessary re-rendering problem. See you on next one!