Avoiding unnecessary rerenders isn’t always the most critical performance issue in React but still it is probably best practice to try to avoid obvious blunders. Take the following example:
const App = () => {
const [cats, setCats] = useState([])
return (
<>
<button
type="button"
onClick={() => {
setCats([...cats, 'http://placekitten.com/200/300']);
}}
>
Add cat
</button>
<Cats cats={cats} />
<Llamas />
</>
)
}
Clicking the button will add another cat to the array of cats
and update state within App
. This will cause App
to rerender which causes all of it’s child components to rerender. It doesn’t matter that Llamas
does not care about cats
, it still rerenders since it is a child of App
.
Obviously, the solution to this problem is to just move the useState
hook into the Cats
component since it is the only component that cares about cats
. App
and Llamas
are not dependent on this piece of state.