Browse Source

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 <dan.abramov@gmail.com>

* nits

* nit
main
Dan Abramov 6 years ago
committed by GitHub
parent
commit
ac4aa6546e
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      content/docs/hooks-faq.md
  2. 39
      content/docs/hooks-reference.md

4
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]);

39
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 `<MyContext.Provider>` above the calling component in the tree.
When the nearest `<MyContext.Provider>` 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 `<MyContext.Consumer>`.
>
>`useContext(MyContext)` only lets you *read* the context and subscribe to its changes. You still need a `<MyContext.Provider>` 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 `<div ref={myRef} />`, 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 && <Child />` and defer showing it with `useEffect(() => { setShowChild(true); }, [])`. This way, the UI doesn't appear broken before hydration.
### `useDebugValue` {#usedebugvalue}

Loading…
Cancel
Save