skip to Main Content

How can I make useEffect have control over the component update?

I have this:

const [data, setData] = useState([]);

useEffect(() => {
  fetch("/api/data")
    .then((res) => res.json())
    .then((res) => {
      setData(res.data);
    })
    .catch((err) => console.error(err));
}, []);

This brings me the information once but if I do something with an item within data the change is not shown in the component that shows that data.

If I use this:

const [data, setData] = useState([]);

useEffect(() => {
  fetch("/api/data")
    .then((res) => res.json())
    .then((res) => {
      setData(res.data);
    })
    .catch((err) => console.error(err));
}, [data]);

It stays in an infinite update loop.

I only want it to change if any data change occurs, so that it doesn’t remain in an infinite loop, how could I achieve this?

Exhibit:

In some useEffects that I have used it asks me for dependencies but this particular one does not do so.

2

Answers


  1. Try using setData instead of setStrores in the code

    const [data, setData] = useState([]);
    
     useEffect(() => {
     fetch("/api/data")
     .then((res) => res.json())
     .then((res) => {
      setData(res.data);
     })
     .catch((err) => console.error(err));
      }, []);
    
    Login or Signup to reply.
  2. In the first case, you will get the res.data once since useEffect without dependency trigger once when component rendered.

    In the second case, setData is called inside useEffect which mean the effect will run infinite time since data being set every render

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search