ref – https://www.glennstovall.com/how-to-use-useeffect-and-other-hooks-in-class-components/
https://stackoverflow.com/questions/58579426/in-useeffect-whats-the-difference-between-providing-no-dependency-array-and-an
The first two arguments of useEffect are a function (didUpdate), and an array of dependencies. the didUpdate function can return a function of its own, a cleanUp function. When a component mounts or the dependencies are updated, didUpdate is called. When the component unmounts, cleanUp is called if present.
In React, functional component use useEffect in order to do something “A” when that component has finished rendering its DOM. This is our subscribing effect. React guarantees the DOM has been updated by the time it runs the effects.
1 2 3 4 5 6 7 |
useEffect( () => { // the effect. // It is an anonymous function and will run at a render. // For each render, a new anonymous function with this code will be given, and run. } ); |
Every time we re-render, we schedule a different effect, replacing the previous one.
1 2 3 4 5 6 7 8 9 10 |
useEffect(() => { // the Effect: // It is an anonymous function and will run after a render. // For each render, a new anonymous function with this code will be given, and run. return () => { // this 'un-effect' is executed before the next freshly created Effect runs } } ); |
React cleans up effects from the previous render before running the effects next time.
And the next effect happens when our components update.
By declaring the dependencies array as empty, you only call the didUpdate and cleanUp functions once each. No dependencies mean no updates.
It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again. In other words, Giving it an empty array acts like componentDidMount as in, it only runs once.
1 2 3 4 5 |
useEffect(() => { const streetView = getStreetView() addListener(streetView, 'on', handlePovChanged()) return clearInstanceListeners }, []) // empty dependency array = only called on mount and unmount |
However, if you give it no argument like so:
1 2 3 |
useEffect(() => { // code }) |
means it runs first on mount and then on every re-render.
Lastly, giving it an array as second argument with any value inside, eg , [variable1] will only execute the code inside your useEffect hook:
- ONCE on mount
- whenever that particular variable (variable1) changes