This is the second post in the series on React Hooks, previously we discussed useState. I am going to try to keep this as short as possible so here we go:
- useEffect lets you preform side effects in function components.
- useEffect is componentDidMount, componentDidUpdate and componentWillUnmount combined.
- It runs something after render!
- By default it runs after the first render and after every update, (there are ways to control it, see below)
- useEffect takes an optional 2nd parameter which is an array of dependencies that will cause the effect to re-run. Instead of running after every update it will only run after any of the dependencies change.
- Unlike componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen.
- Effects without Cleanup
- Manual DOM mutations
- Fetching Data
- Effects with Cleanup
- Subscriptions / Event listeners
Effects without Cleanup
Manual DOM mutations
Making a network request (note: Hooks are not the final solution to making network requests in React, Suspense is coming for that). I have added comments into the code on some gotchas you need to be careful with.
Effects with Cleanup
Subscriptions / Event listeners
Subscriptions / Event listeners should always be clean up when they are not needed that way we can avoid memory leaks.
Well, that is useEffect, I hope you enjoyed this post, you will be using useEffect everywhere in your application. As you use it you will become more familiar with its in and out.
Until next time,