react-effects Flashcards
When is a component “mounted” to the DOM?
Triggering a render (delivering the guest’s order to the kitchen)
Rendering the component (preparing the order in the kitchen)
Committing to the DOM (placing the order on the table)
What is a React Effect?
Effects let you run some code after rendering so that you can synchronize your component with some system outside of React.
Effects let you specify side effects that are caused by rendering itself, rather than by a particular event.
When should you use an Effect and when should you not use an Effect?
Keep in mind that Effects are typically used to “step out” of your React code and synchronize with some external system. This includes browser APIs, third-party widgets, network, and so on. If your Effect only adjusts some state based on other state, you might not need an Effect.
When do Effects run?
By default, useEffect runs after each render of the component where it’s called.
The effect runs when the component is mounted, and whether or not it runs on subsequent updates is determined by an array of dependencies passed
What function is used to declare an Effect?
useEffect
What are Effect dependencies and how do you declare them?
You can tell React to skip unnecessarily re-running the Effect by specifying an array of dependencies as the second argument to the useEffect call. Start by adding an empty [] array to the above example on line 14:
Specifying [isPlaying] as the dependency array tells React that it should skip re-running your Effect if isPlaying is the same as it was during the previous render.
Why would you want to clean up from an Effect?
Prevent unexpected errors, so we dont keep things running when they dont have to be or when something unmounts
How do you clean up from an Effect?
you return a function that disconnects
When does the cleanup function run?
However, it is pertinent to note that the useEffect cleanup function does not only run when our component wants to unmount, it also runs right before the execution of the next scheduled effect.
React will call your cleanup function each time before the Effect runs again, and one final time when the component unmounts (gets removed).