简体   繁体   中英

stop infinite loop in useEffect

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM