This post aims to help those who have worked with and studied React Hooks previously and want a quick brush up on key topics.
What type of component can make use of Hooks?
Where can you use a hook inside of a component?
Hooks must always be used at the top level of a component and outside of any control structures.
What to do if you need a useEffect hook to handle logic conditionally?
Put the condition inside the hook and pass a callback function to the hook.
Why do hooks need to be called in the same order each time?
Because this is how React keeps track of which state belongs to each useState hook. By keeping the order the same on each render React is able to associate some local state with each hook.
When are useEffect hooks called?
By default they are called after every render, both the first render and on every DOM update.
How do you handle side effect cleanup when using useEffect?
Some side effects need to be cleaned up before a component is unmounted. To do this with useEffect, return a function from your useEffect hook, that function will be executed before the component is destroyed and you can handle any cleanup inside of it.
What are a few examples of side effects you would want to handle inside a useEffect hook?
- Making any network request.
- Updating browser api attribute like document.title, which is imperative.
- Handling any imperative updates, like the afore mentioned or file inputs.
- Using setInterval and clearing the interval on unmount.