0
votes

The react application that I'm working on triggers the userEffect function if the prop value changes from an empty array to another empty array.

I'm getting query params from the page and passing them down in a component that re-renders if any of the query param array changes. But the issue is that the useEffect function triggers and re-renders the component even if the query param array changed from [] to [].

I know that [] !== [], maybe that's what causing the issue. But is there a way that that the application can prevent triggering the useEffect function in the first place?

Heres a codesandbox demo: https://codesandbox.io/s/vibrant-greider-qgjgs?file=/src/App.js

3
It's unclear exactly what you're trying to do. When exactly do you want the useEffect to run? - jered
@jered , Just don't want to trigger it if the prop changes from [] to [] - Prottay Rudra
why not just use if-else inside useEffect? It will still trigger the function but the function can still decide what to do - Muhammed B. Aydemir
@MuhammedB.Aydemir, maybe I could use an if statement to check for length. what happens if the query param changes from ['some-data'] to []`. How do you handle that? - Prottay Rudra
Is it an issue (performance) if the component rerenders for this edge-case? What is the concern? - Drew Reese

3 Answers

1
votes

you are assigning a new reference to the test hence it is triggering an update.

you should reassign the same array and to manipulation in it.

   const handleClick = () => {
   const arr = test
    setTest(arr);
  };
1
votes

You can either create your own custom hook that checks for deep equality on each of the dependency array items or use one like use-deep-compare-effect

0
votes

In addition to the answer above, you can also use React.memo as a way to do a comparison check between previous props and new props. If your props is somewhat complicated, you can probably add Lodash on top of it too.