Arrays, like objects, are recreated on every re-render when defined inside a React functional component. The behavior is similar to that of objects because both arrays and objects are reference types in JavaScript.
When you define an array inside a React functional component, a new array is created on every re-render. This is due to the fact that the old values inside the function body are garbage-collected, and a new array is instantiated. As a result:
- The array has a new reference in memory on every re-render;
- The new array is not equal to the array from the previous re-render when doing
Object.is()
or shallow comparison.
For example:
// MyComponent.jsx import React, { useState, useEffect } from 'react'; export function MyComponent() { const [foo, setFoo] = useState(''); // every time `foo` changes, this will be a different array const myArray = [1, 2, 3]; useEffect(() => { console.log('effect was run'); }, [myArray]); return ( <button onClick={() => setFoo(Math.random())}>Foo</button> ); }
In this example, changing the reactive value "foo
" will cause the component to re-render, leading to the recreation of the "myArray
" on each re-render. Consequently, the useEffect()
callback will be triggered each time due to the changing array reference.
To prevent unnecessary re-renders, similar strategies can be applied as with objects, such as using the useState()
hook for state management or memoizing the array using useMemo()
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.