I am in a coding bootcamp I have a tutor that insists that [`$events'] will work in the code but have not found fix. I know you discuss ['$events'] as not being adequate is there anywhere else in the code that can be changed to make this work? //Copy reason why stringify (idea where they coming from) Why Stringify? Why use ${allLocations} and not just allLocations? Well, it’s important to always avoid directly putting complex data-type variables into useEffect’s dependency array.
This is because such variables have memory references stored in them that point somewhere else in the memory to where the array values are.
This is in contrast to primitive data-type variables, such as strings.
Take a look at the following illustrations to get a better idea:
Diagram demonstrating potential memory reference difference when using complex data type variables
Figure 4. Memory reference #6441AFFF doesn't equal memory reference #FCC3177A. As a result, useEffect() will think the state has been changed, despite both pointing to arrays that have the same values. The useEffect() callback will be executed, which isn't supposed to happen.
Now let’s look at a situation where useEffect()'s dependency array contains primitive values, such as strings. In this case, the variable stores the actual value rather than a reference to the value. Let’s assume that you have a string dependency, name, where both the old and new values are "test":
Diagram showing variable storing actual value, rather than a reference to the value
Figure 5. "test" does equal "test". As a result, useEffect() will think the state hasn't been changed, and the callback won't be executed, which is the expected behavior.
This is why you would use ${allLocations} to compare the lists after they’re converted to a string (you could also use JSON.stringify(allLocations) to convert it to a string). useEffect() will compare string representations of the arrays, not their memory references.
Keep in mind this is one of many ways that you can compare arrays or objects. In fact, this is one of the more inefficient options, but since it’s so simple, it’s easy to use here.
For a more advanced approach, you could use React hooks like useCallback and useMemo.