Reputation:
I got infinite loop running below code, basically I try to sync props's state with local state
const SomeComponent = ({ ids = [] }) => {
const selectedIds = useStore(reduxStore);
const [_, setSelectedIds] = useState(selectedIds);
useEffect(() => {
setSelectedIds(ids);
}, [ids]);
};
I can't do if(ids.length) setSelectedIds(ids)
because they will be a case where the setSelectedIds is [], I want to sync it too. But I got infinite loop.
Upvotes: 0
Views: 69
Reputation: 15540
Your problem is you set { ids = [] }
with []
as a default value. If you don't pass ids
to SomeComponent
, it will keep initializing ids
as a new fresh array []
that will cause continuous re-renderings
Representing your problem
const { useEffect, useState } = React
const SomeComponent = ({ ids = [] }) => {
const [_, setSelectedIds] = useState([]);
useEffect(() => {
setSelectedIds(ids);
}, [ids]);
console.log('here')
return null
};
ReactDOM.render(
<SomeComponent/>,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The possible fix is you should set { ids }
instead of being with a default value (if it's empty, leave it as it is)
const { useEffect, useState } = React
const SomeComponent = ({ ids }) => {
const [_, setSelectedIds] = useState([]);
useEffect(() => {
setSelectedIds(ids);
}, [ids]);
console.log('here')
return null
};
ReactDOM.render(
<SomeComponent/>,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1