4

I realized that

useEffect(() => {

});

without the second argument of the array will cause the function to run every single time.

However, since we are concerned with some data or ID to display (the React docs of setting the document's title) or data to fetch, in what real practical example would we actually want it to always run? I can only think of cases where we only want it to run once, or if we depend on something, such as id or some value, but never "always run". What is just one real use so that we can see that it is actually practical? (and so that we can relate this feature with an actually practical use case in the world). What is one real world example of use? I don't think this is opinion based.

Stefanie Gauss
  • 425
  • 3
  • 9
  • 1
    I guess there aren't really any real life use cases but it could be used to e.g. create some debugging output after every render of that component. – trixn Feb 26 '21 at 17:06
  • this question is so "not opinion based"... can anyone find one case? Nobody can state one case and some guy come in saying "oh it is just your opinion". It really pushes the human race forward, or turned the other way – Stefanie Gauss Feb 27 '21 at 03:47
  • After more thinking, I actually came up with a case: let's say if it is a component, and there is a stock price quote, or a system OK signal. The manager or PM said, "Ok, if this component doesn't repaint, it is ok, but whenever this component repaints for any data, we want the stock price quote (or system OK green light or red light) to be updated, NO MATTER WHAT." So this "no matter what" is that we always use `useEffect()` to fetch some data, regardless of what dependencies there can be. So instead of making a full list of what could cause the component to update, just omit the array – Stefanie Gauss Feb 27 '21 at 07:30
  • A use case I ran across is creating a `usePrevious` hook. Like so.. ``` function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; } ``` – Nathan Hall Mar 14 '21 at 21:25
  • [When to use useEffect without dependencies vs. direct assignment?](https://stackoverflow.com/a/66804905/2873538) – Ajeet Shah Apr 30 '21 at 07:11

0 Answers0