diff --git a/README.md b/README.md index 8fa0cb6..503fd9d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_849 TILs and counting..._ +_850 TILs and counting..._ --- @@ -577,6 +577,7 @@ _849 TILs and counting..._ - [@reach/router Renders To A Div](react/reach-router-renders-to-a-div.md) - [Read Only Input Elements](react/read-only-input-elements.md) - [Rendering Multiple Nodes With Fragments](react/rendering-multiple-nodes-with-fragments.md) +- [Specifying Dependencies Of A useEffect Hook](react/specifying-dependencies-of-a-useeffect-hook.md) - [Spelunking Through Components With Enzyme's Dive](react/spelunking-through-components-with-enzymes-dive.md) - [Sync Your react-router State With Redux](react/sync-your-react-router-state-with-redux.md) - [Test Files In create-react-app](react/test-files-in-create-react-app.md) diff --git a/react/specifying-dependencies-of-a-useeffect-hook.md b/react/specifying-dependencies-of-a-useeffect-hook.md new file mode 100644 index 0000000..e8d0d04 --- /dev/null +++ b/react/specifying-dependencies-of-a-useeffect-hook.md @@ -0,0 +1,40 @@ +# Specifying Dependencies Of A useEffect Hook + +The `useEffect` hook is all about performing side-effects. For instance, +you'll want to place API calls within `useEffect` hooks. + +The dependency array -- the second argument to `useEffect` -- is where you +declare all of the values that are depended on within the `useEffect`. If +you're making an API call, this array is likely made up of parameters passed to +that call. + +Here is a contrived example of what that could look like: + +```javascript +const apiCall = (opts) => Promise.resolve(opts); +const [param1, param2, param3] = [1,2,3]; + +useEffect(() => { + const handleApiCall = async () => { + apiCall({ param1, param2, param3 }) + .then((data) => { + // do something with the data + }) + .catch((error) => { + // do something with the error + }); + } + + handleApiCall(); +}, [param1, param2, param3]); +``` + +If you don't specify all of the values used in the body of the `useEffect`, you +are opening yourself up to potentially incorrect code. It is safer to specify +all of them. The [`exhaustive-deps` +rule](https://www.npmjs.com/package/eslint-plugin-react-hooks) can help. + +[This +section](https://overreacted.io/a-complete-guide-to-useeffect/#what-happens-when-dependencies-lie) +of Dan Abramov's "A Complete Guide to useEffect" does an excellent job of +showing how things can go wrong when you lie to React about your dependencies.