API memo in React
Before we look at the next hook, it's worth mentioning the useful memo API, which helps us avoid re-rendering a component if its props remain unchanged.
Let's look at this with an example. Let's create a component App, which will have two inputs, in which, let's say, the first and last name are entered:
return (
<div>
<label>
name:
<input value={name} onChange={(e) => setName(e.target.value)} />
</label>
<br />
<label>
surname:
<input value={surn} onChange={(e) => setSurn(e.target.value)} />
</label>
</div>
);
Let's add states for them to the beginning of the component:
const [name, setName] = useState('');
const [surn, setSurn] = useState('');
Let's also make a child component Child.js, let it output a greeting, which will display the entered name. Also, the line 'child render' will be output to the console each time this component is rendered:
function Child({ name }) {
console.log('child render');
return <h3>Hello {name}!</h3>;
}
Let's add Child to the main component's layout after the last input and pass it the name as a prop:
<Child name={name} />
We import it into the main component:
import Child from './Child';
Now let's open the console and enter the first and last name in the input fields. Here we will see that even when entering characters in the last name field, our child component will be redrawn each time. No problem, because we have a small component. But imagine if this component displayed a large amount of data and at the same time, it was redrawn each time.
Now let's wrap the child component in memo and see how the rendering changes. First, import memo into it:
import { memo } from 'react';
Then we create a new variable and assign it our Child wrapped in memo. We get the following function expression:
const Child = memo( function Child({ name }) {
console.log('child render');
return <h3>Hello {name}!</h3>;
});
Let's open the console and enter the first and last name into the fields again. Now we see that when entering the last name, our child component does not re-render.
It is important to remember that this will not work if the states used by the component or the context using the changes change while the props remain unchanged.
Take the App component code we made in this tutorial, leave it with only the first input. Create a React component Text containing a paragraph with the text 'long text', and place it in App after the input.
In the Text component, add the line console.log('text render');. Make sure that when you type characters into the input, the Text component re-renders every time.
Now wrap the Text component in memo. Make sure that when you type characters into the input, the Text component does not re-render.