Search code examples
reactjsasynchronousaxiosinfinite-loopuse-effect

Infinite re-render in functional react component


I am trying to set the state of a variable "workspace", but when I console log the data I get an infinite loop. I am calling the axios "get" function inside of useEffect(), and console logging outside of this loop, so I don't know what is triggering all the re-renders. I have not found an answer to my specific problem in this question. Here's my code:

function WorkspaceDynamic({ match }) {
  const [proposals, setProposals] = useState([{}]);
  useEffect(() => {
    getItems();
  });

  const getItems = async () => {
    const proposalsList = await axios.get(
      "http://localhost:5000/api/proposals"
    );
    setProposals(proposalsList.data);
  };

  const [workspace, setWorkspace] = useState({});
  function findWorkspace() {
    proposals.map((workspace) => {
      if (workspace._id === match.params.id) {
        setWorkspace(workspace);
      }
    });
  }

Does anyone see what might be causing the re-render? Thanks!


Solution

  • The effect hook runs every render cycle, and one without a dependency array will execute its callback every render cycle. If the effect callback updates state, i.e. proposals, then another render cycle is enqueued, thus creating render looping.

    If you want to only run effect once when the component mounts then use an empty dependency array.

    useEffect(() => {
      getItems();
    }, []);
    

    If you want it to only run at certain time, like if the match param updates, then include a dependency in the array.

    useEffect(() => {
      getItems();
    }, [match]);