React.useEffect is keep executing for every button click. Not sure why ? Someone can help ?
const Dropdown1 = ({
selectedItems = [],
}) => {
const [open, setOpen] = useState(false);
useEffect(() => {
console.log(selectedItems);
}, [selectedItems]);
return (
<Button
className="button"
onClick={() => setOpen((prev) => !prev)}
>
Select
</Button>
);
};
// Render
<Dropdown1 />
Because of this:
const Dropdown1 = ({ selectedItems = [] }) => {
The selectedItems
value isn’t state-driven, nor is it a prop received by the component:
<Dropdown1 />
The empty array is a default value for the function parameter. And every time that function executes, it creates an empty array to satisfy that default parameter. Each such array is a new instance, so it triggers the useEffect
dependency.
Instead, supply an instance as a prop:
<Dropdown1 selectedItems={[]} />
In this case the value isn’t being created by the function, but is being supplied to the function. Since the parent component doesn’t re-render, it’s the same array reference and doesn’t trigger the useEffect
dependency.
2