From ac4aa6546e413bc6bdc6d8191081b739fbc6fb27 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Tue, 19 Mar 2019 17:12:44 +0000 Subject: [PATCH] Add more explanations to Hooks API page (#1845) * Add more explanations to API page * static * add info about useLayoutEffect * Update content/docs/hooks-reference.md Co-Authored-By: gaearon * nits * nit --- content/docs/hooks-faq.md | 4 ++-- content/docs/hooks-reference.md | 39 ++++++++++++++++++++++++++++----- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 1e68b379..7d295329 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -908,7 +908,7 @@ function Form() { const [text, updateText] = useState(''); const textRef = useRef(); - useLayoutEffect(() => { + useEffect(() => { textRef.current = text; // Write it to the ref }); @@ -949,7 +949,7 @@ function useEventCallback(fn, dependencies) { throw new Error('Cannot call an event handler while rendering.'); }); - useLayoutEffect(() => { + useEffect(() => { ref.current = fn; }, [fn, ...dependencies]); diff --git a/content/docs/hooks-reference.md b/content/docs/hooks-reference.md index 4daf0f19..f2cc087d 100644 --- a/content/docs/hooks-reference.md +++ b/content/docs/hooks-reference.md @@ -97,6 +97,8 @@ const [state, setState] = useState(() => { If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the [`Object.is` comparison algorithm](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description).) +Note that React may still need to render that specific component again before bailing out. That shouldn't be a concern because React won't unnecessarily go "deeper" into the tree. If you're doing expensive calculations while rendering, you can optimize them with `useMemo`. + ### `useEffect` {#useeffect} ```js @@ -173,12 +175,24 @@ The array of dependencies is not passed as arguments to the effect function. Con ### `useContext` {#usecontext} ```js -const context = useContext(Context); +const value = useContext(MyContext); ``` -Accepts a context object (the value returned from `React.createContext`) and returns the current context value, as given by the nearest context provider for the given context. +Accepts a context object (the value returned from `React.createContext`) and returns the current context value for that context. The current context value is determined by the `value` prop of the nearest `` above the calling component in the tree. + +When the nearest `` above the component updates, this Hook will trigger a rerender with the latest context `value` passed to that `MyContext` provider. -When the provider updates, this Hook will trigger a rerender with the latest context value. +Don't forget that the argument to `useContext` must be the *context object itself*: + + * **Correct:** `useContext(MyContext)` + * **Incorrect:** `useContext(MyContext.Consumer)` + * **Incorrect:** `useContext(MyContext.Provider)` + +>Tip +> +>If you're familiar with the context API before Hooks, `useContext(MyContext)` is equivalent to `static contextType = MyContext` in a class, or to ``. +> +>`useContext(MyContext)` only lets you *read* the context and subscribe to its changes. You still need a `` above in the tree to *provide* the value for this context. ## Additional Hooks {#additional-hooks} @@ -285,6 +299,8 @@ function Counter({initialCount}) { If you return the same value from a Reducer Hook as the current state, React will bail out without rendering the children or firing effects. (React uses the [`Object.is` comparison algorithm](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description).) +Note that React may still need to render that specific component again before bailing out. That shouldn't be a concern because React won't unnecessarily go "deeper" into the tree. If you're doing expensive calculations while rendering, you can optimize them with `useMemo`. + ### `useCallback` {#usecallback} ```js @@ -356,7 +372,16 @@ function TextInputWithFocusButton() { } ``` -Note that `useRef()` is useful for more than the `ref` attribute. It's [handy for keeping any mutable value around](/docs/hooks-faq.html#is-there-something-like-instance-variables) similar to how you'd use instance fields in classes. +Essentially, `useRef` is like a "box" that can hold a mutable value in its `.current` property. + +You might be familiar with refs primarily as a way to [access the DOM](/docs/refs-and-the-dom.html). If you pass a ref object to React with `
`, React will set its `.current` property to the corresponding DOM node whenever that node changes. + +However, `useRef()` is useful for more than the `ref` attribute. It's [handy for keeping any mutable value around](/docs/hooks-faq.html#is-there-something-like-instance-variables) similar to how you'd use instance fields in classes. + +This works because `useRef()` creates a plain JavaScript object. The only difference between `useRef()` and creating a `{current: ...}` object yourself is that `useRef` will give you the same ref object on every render. + +Keep in mind that `useRef` *doesn't* notify you when its content changes. Mutating the `.current` property doesn't cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a [callback ref](/docs/hooks-faq.html#how-can-i-measure-a-dom-node) instead. + ### `useImperativeHandle` {#useimperativehandle} @@ -389,7 +414,11 @@ Prefer the standard `useEffect` when possible to avoid blocking visual updates. > Tip > -> If you're migrating code from a class component, `useLayoutEffect` fires in the same phase as `componentDidMount` and `componentDidUpdate`, so if you're unsure of which effect Hook to use, it's probably the least risky. +> If you're migrating code from a class component, note `useLayoutEffect` fires in the same phase as `componentDidMount` and `componentDidUpdate`. However, **we recommend starting with `useEffect` first** and only trying `useLayoutEffect` if that causes a problem. +> +>If you use server rendering, keep in mind that *neither* `useLayoutEffect` nor `useEffect` can run until the JavaScript is downloaded. This is why React warns when a server-rendered component contains `useLayoutEffect`. To fix this, either move that logic to `useEffect` (if it isn't necessary for the first render), or delay showing that component until after the client renders (if the HTML looks broken until `useLayoutEffect` runs). +> +>To exclude a component that needs layout effects from the server-rendered HTML, render it conditionally with `showChild && ` and defer showing it with `useEffect(() => { setShowChild(true); }, [])`. This way, the UI doesn't appear broken before hydration. ### `useDebugValue` {#usedebugvalue}