From 446da409300d43e8b779a398946945a0a3ad5816 Mon Sep 17 00:00:00 2001 From: Ryan Cogswell <287804+ryancogswell@users.noreply.github.com> Date: Mon, 13 May 2019 10:58:49 -0500 Subject: [PATCH] Clarify useEffect behavior for empty dependency array The current wording "If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument." is confusing some people. They are interpreting this as meaning that the effect will run on mount **and** on unmount. See cbdev420's comment on my answer [here](https://stackoverflow.com/questions/56115295/how-to-set-up-an-event-listener-and-remove-it-after-first-fired-event-using-reac/56115564?noredirect=1#comment98864939_56115564). --- content/docs/hooks-reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-reference.md b/content/docs/hooks-reference.md index 24145eac218..243ea019b65 100644 --- a/content/docs/hooks-reference.md +++ b/content/docs/hooks-reference.md @@ -163,7 +163,7 @@ Now the subscription will only be recreated when `props.source` changes. > >If you use this optimization, make sure the array includes **all values from the component scope (such as props and state) that change over time and that are used by the effect**. Otherwise, your code will reference stale values from previous renders. Learn more about [how to deal with functions](/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies) and what to do when the [array values change too often](/docs/hooks-faq.html#what-can-i-do-if-my-effect-dependencies-change-too-often). > ->If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array (`[]`) as a second argument. This tells React that your effect doesn't depend on *any* values from props or state, so it never needs to re-run. This isn't handled as a special case -- it follows directly from how the dependencies array always works. +>If you want to run an effect and clean it up only once (run on mount and clean it up on unmount), you can pass an empty array (`[]`) as a second argument. This tells React that your effect doesn't depend on *any* values from props or state, so it never needs to re-run. This isn't handled as a special case -- it follows directly from how the dependencies array always works. > >If you pass an empty array (`[]`), the props and state as inside the effect will always have their initial values. While passing `[]` as the second argument is closer to the familiar `componentDidMount` and `componentWillUnmount` mental model, there are usually [better](/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies) [solutions](/docs/hooks-faq.html#what-can-i-do-if-my-effect-dependencies-change-too-often) to avoid re-running effects too often. Also, don't forget that React defers running `useEffect` until after the browser has painted, so doing extra work is less of a problem. >