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().