In react useEffect life cycle, i am getting infinite result

Asked
Active3 hr before
Viewed126 times

9 Answers

react
90%

That's because, you're setting the state in useEffects and hence triggering it again and again... , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Whenever, state changes, useEffects get triggered if the same state has been passed as a dependency in it. That's exactly what you've done.

Pretag
 Pretag team - issue, fix, solve, resolve
88%

As a result, “useEffect()” will run again and update the state. Next, the whole process repeats again, and you're trapped inside an infinite loop.,The “useEffect()”, will run after the initial render, then invoke the “fetchUser()”.,Then, there is“useEffect()” which will call the “fetchUser()” after rendering a DOM element.

Pretag
 Pretag team - issue, fix, solve, resolve
72%

What other infinite loop pitfalls when using useEffect() do you know?,If you aren’t familiar with useEffect(), I recommend reading my post A Simple Explanation of React.useEffect() before continuing. Having good fundamental knowledge of a non-trivial subject helps bypass the rookie mistakes.,it generates an infinite loop of component re-renderings.

import { useEffect, useState } from 'react';

function CountInputChanges() {
  const [value, setValue] = useState('');
  const [count, setCount] = useState(-1);

  useEffect(() => setCount(count + 1));
  const onChange = ({ target }) => setValue(target.value);

  return (
    <div>
      <input type="text" value={value} onChange={onChange} />
      <div>Number of changes: {count}</div>
    </div>
  )
}
load more v
65%

I really liked my first experience with the useEffect Hook. Now it’s no longer necessary to refactor a functional component to a class component. At least not just because you need state or some lifecycle methods. ,That means if you modify the components state inside useEffect, it will cause a re-render of the component, which again causes the execution of useEffect. ,why I can’t find this piece of advice in React documentation, that’s is really frustrating, that React community still keeps documentation as simple as possible for newbie’s only.

So there it is – our Hook that is going to load some Users from an API to display it in a UserList component:

  useEffect(() => {
     axios.get("https://jsonplaceholder.typicode.com/users").then(result => setData(result.data));
  });
load more v
75%

As we will see later, the useEffect Hook fosters separation of concerns and reduces code duplication. For example, the official React docs show that you can avoid the duplicated code that results from lifecycle methods with one useEffect statement.,I hope these example have convinced you that working with effects is different from lifecycle methods and that it is ultimately not beneficial to try to mimic these methods.,For example, now that I have dealt with useEffect for quite some time, I have realized that it is key to fully understand the component flow of functional components. As such, this aspect is an important topic in this article.

Pretag
 Pretag team - issue, fix, solve, resolve
40%

componentDidMount lifecycle,How to replicate the componentDidMount lifecycle,React.useEffect is a basic hook that gets triggered on a combination of 3 React component lifecycles:

Pretag
 Pretag team - issue, fix, solve, resolve
22%

Have you ever faced this issue that your useEffect hook gets executed multiple times? Maybe sometimes it goes into the infinite loop?,If you run this code, you can see that the useEffect hook will be called only after executing all the code inside our component. The class equivalent code of this snippet would be something like this:,I wrote this blog to show why useEffect hook gets executed multiple times and how to prevent this by passing the second argument. I had discussed about the best practices too many times with a lot of people in my organisation and also in a lot of meetups/conferences but we never concluded anything unanimously. But I would love to know your thoughts. You can comment here or simply DM me on Twitter.

import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    console.log('Hello from useEffect!');
  });
  console.log('Hello from the component!');

  return (
    <div>Hello World</div>
  );
}

export default App;
load more v
60%

Run useEffect on State Change,Fetch Data With useEffect,Prevent useEffect From Running Every Render

import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';

function LifecycleDemo() {
  // Pass useEffect a function
  useEffect(() => {
    // This gets called after every render, by default
    // (the first one, and every one after that)
    console.log('render!');

    // If you want to implement componentWillUnmount,
    // return a function from here, and React will call
    // it prior to unmounting.
    return () => console.log('unmounting...');
  })

  return "I'm a lifecycle demo";
}

function App() {
  // Set up a piece of state, so that we have
  // a way to trigger a re-render.
  const [random, setRandom] = useState(Math.random());

  // Set up another piece of state to keep track of
  // whether the LifecycleDemo is shown or hidden
  const [mounted, setMounted] = useState(true);

  // This function will change the random number,
  // and trigger a re-render (in the console,
  // you'll see a "render!" from LifecycleDemo)
  const reRender = () => setRandom(Math.random());

  // This function will unmount and re-mount the
  // LifecycleDemo, so you can see its cleanup function
  // being called.
  const toggle = () => setMounted(!mounted);

  return (
    <>
      <button onClick={reRender}>Re-render</button>
      <button onClick={toggle}>Show/Hide LifecycleDemo</button>
      {mounted && <LifecycleDemo/>}
    </>
  );
}

ReactDOM.render(<App/>, document.querySelector('#root'));
load more v
48%

One of my favorite things about React is that it unifies describing the initial render result and the updates. This reduces the entropy of your program.,Whenever we update the state, React calls our component. Each render result “sees” its own counter state value which is a constant inside our function.,React synchronizes the DOM according to our current props and state. There is no distinction between a “mount” or an “update” when rendering.

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v

Other "react-undefined" queries related to "In react useEffect life cycle, i am getting infinite result"