From 352d1ec3bb4df1efbf13933d94fb93bc8c29ced3 Mon Sep 17 00:00:00 2001 From: Dmitry Litsman Date: Wed, 27 Mar 2024 12:31:43 +0000 Subject: [PATCH 1/4] Update context to Context in the docs where appropriate --- src/content/blog/2022/03/29/react-v18.md | 4 +- src/content/learn/keeping-components-pure.md | 4 +- .../learn/lifecycle-of-reactive-effects.md | 2 +- src/content/learn/managing-state.md | 12 +-- .../learn/passing-data-deeply-with-context.md | 74 +++++++++---------- src/content/learn/rendering-lists.md | 2 +- .../scaling-up-with-reducer-and-context.md | 58 +++++++-------- src/content/learn/typescript.md | 6 +- .../reference/react-dom/createPortal.md | 4 +- src/content/reference/react-dom/preinit.md | 2 +- src/content/reference/react/Component.md | 6 +- src/content/reference/react/PureComponent.md | 2 +- src/content/reference/react/StrictMode.md | 2 +- src/content/reference/react/apis.md | 2 +- src/content/reference/react/cache.md | 2 +- src/content/reference/react/cloneElement.md | 10 +-- src/content/reference/react/createContext.md | 48 ++++++------ src/content/reference/react/hooks.md | 6 +- src/content/reference/react/memo.md | 8 +- src/content/reference/react/use.md | 18 ++--- src/content/reference/react/useContext.md | 68 ++++++++--------- src/content/reference/react/useRef.md | 2 +- .../reference/react/useSyncExternalStore.md | 2 +- .../components-and-hooks-must-be-pure.md | 4 +- src/content/reference/rules/index.md | 2 +- 25 files changed, 175 insertions(+), 175 deletions(-) diff --git a/src/content/blog/2022/03/29/react-v18.md b/src/content/blog/2022/03/29/react-v18.md index 743404c1af9..64a08cf50c5 100644 --- a/src/content/blog/2022/03/29/react-v18.md +++ b/src/content/blog/2022/03/29/react-v18.md @@ -285,7 +285,7 @@ See [How to Upgrade to React 18](/blog/2022/03/08/react-18-upgrade-guide) for st * Improve memory usage. ([#21039](https://github.com/facebook/react/pull/21039) by [@bgirard](https://github.com/bgirard)) * Improve messages if string coercion throws (Temporal.*, Symbol, etc.) ([#22064](https://github.com/facebook/react/pull/22064) by [@justingrant](https://github.com/justingrant)) * Use `setImmediate` when available over `MessageChannel`. ([#20834](https://github.com/facebook/react/pull/20834) by [@gaearon](https://github.com/gaearon)) -* Fix context failing to propagate inside suspended trees. ([#23095](https://github.com/facebook/react/pull/23095) by [@gaearon](https://github.com/gaearon)) +* Fix Context failing to propagate inside suspended trees. ([#23095](https://github.com/facebook/react/pull/23095) by [@gaearon](https://github.com/gaearon)) * Fix `useReducer` observing incorrect props by removing the eager bailout mechanism. ([#22445](https://github.com/facebook/react/pull/22445) by [@josephsavona](https://github.com/josephsavona)) * Fix `setState` being ignored in Safari when appending iframes. ([#23111](https://github.com/facebook/react/pull/23111) by [@gaearon](https://github.com/gaearon)) * Fix a crash when rendering `ZonedDateTime` in the tree. ([#20617](https://github.com/facebook/react/pull/20617) by [@dimaqq](https://github.com/dimaqq)) @@ -312,7 +312,7 @@ See [How to Upgrade to React 18](/blog/2022/03/08/react-18-upgrade-guide) for st ### React DOM Server {/*react-dom-server-1*/} * Add the new streaming renderer. ([#14144](https://github.com/facebook/react/pull/14144), [#20970](https://github.com/facebook/react/pull/20970), [#21056](https://github.com/facebook/react/pull/21056), [#21255](https://github.com/facebook/react/pull/21255), [#21200](https://github.com/facebook/react/pull/21200), [#21257](https://github.com/facebook/react/pull/21257), [#21276](https://github.com/facebook/react/pull/21276), [#22443](https://github.com/facebook/react/pull/22443), [#22450](https://github.com/facebook/react/pull/22450), [#23247](https://github.com/facebook/react/pull/23247), [#24025](https://github.com/facebook/react/pull/24025), [#24030](https://github.com/facebook/react/pull/24030) by [@sebmarkbage](https://github.com/sebmarkbage)) -* Fix context providers in SSR when handling multiple requests. ([#23171](https://github.com/facebook/react/pull/23171) by [@frandiox](https://github.com/frandiox)) +* Fix Context providers in SSR when handling multiple requests. ([#23171](https://github.com/facebook/react/pull/23171) by [@frandiox](https://github.com/frandiox)) * Revert to client render on text mismatch. ([#23354](https://github.com/facebook/react/pull/23354) by [@acdlite](https://github.com/acdlite)) * Deprecate `renderToNodeStream`. ([#23359](https://github.com/facebook/react/pull/23359) by [@sebmarkbage](https://github.com/sebmarkbage)) * Fix a spurious error log in the new server renderer. ([#24043](https://github.com/facebook/react/pull/24043) by [@eps1lon](https://github.com/eps1lon)) diff --git a/src/content/learn/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md index 6d4f55763fa..750fc362ee6 100644 --- a/src/content/learn/keeping-components-pure.md +++ b/src/content/learn/keeping-components-pure.md @@ -149,7 +149,7 @@ In general, you should not expect your components to be rendered in any particul #### Detecting impure calculations with StrictMode {/*detecting-impure-calculations-with-strict-mode*/} -Although you might not have used them all yet, in React there are three kinds of inputs that you can read while rendering: [props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [context.](/learn/passing-data-deeply-with-context) You should always treat these inputs as read-only. +Although you might not have used them all yet, in React there are three kinds of inputs that you can read while rendering: [props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [Context.](/learn/passing-data-deeply-with-context) You should always treat these inputs as read-only. When you want to *change* something in response to user input, you should [set state](/learn/state-a-components-memory) instead of writing to a variable. You should never change preexisting variables or objects while your component is rendering. @@ -219,7 +219,7 @@ Every new React feature we're building takes advantage of purity. From data fetc * **It minds its own business.** It should not change any objects or variables that existed before rendering. * **Same inputs, same output.** Given the same inputs, a component should always return the same JSX. * Rendering can happen at any time, so components should not depend on each others' rendering sequence. -* You should not mutate any of the inputs that your components use for rendering. That includes props, state, and context. To update the screen, ["set" state](/learn/state-a-components-memory) instead of mutating preexisting objects. +* You should not mutate any of the inputs that your components use for rendering. That includes props, state, and Context. To update the screen, ["set" state](/learn/state-a-components-memory) instead of mutating preexisting objects. * Strive to express your component's logic in the JSX you return. When you need to "change things", you'll usually want to do it in an event handler. As a last resort, you can `useEffect`. * Writing pure functions takes a bit of practice, but it unlocks the power of React's paradigm. diff --git a/src/content/learn/lifecycle-of-reactive-effects.md b/src/content/learn/lifecycle-of-reactive-effects.md index 3dc9a75f02b..c6edfb57556 100644 --- a/src/content/learn/lifecycle-of-reactive-effects.md +++ b/src/content/learn/lifecycle-of-reactive-effects.md @@ -554,7 +554,7 @@ However, if you [think from the Effect's perspective,](#thinking-from-the-effect Props and state aren't the only reactive values. Values that you calculate from them are also reactive. If the props or state change, your component will re-render, and the values calculated from them will also change. This is why all variables from the component body used by the Effect should be in the Effect dependency list. -Let's say that the user can pick a chat server in the dropdown, but they can also configure a default server in settings. Suppose you've already put the settings state in a [context](/learn/scaling-up-with-reducer-and-context) so you read the `settings` from that context. Now you calculate the `serverUrl` based on the selected server from props and the default server: +Let's say that the user can pick a chat server in the dropdown, but they can also configure a default server in settings. Suppose you've already put the settings state in a [Context](/learn/scaling-up-with-reducer-and-context) so you read the `settings` from that Context. Now you calculate the `serverUrl` based on the selected server from props and the default server: ```js {3,5,10} function ChatRoom({ roomId, selectedServerUrl }) { // roomId is reactive diff --git a/src/content/learn/managing-state.md b/src/content/learn/managing-state.md index 93bcc10fd61..cb3fbbc580a 100644 --- a/src/content/learn/managing-state.md +++ b/src/content/learn/managing-state.md @@ -697,11 +697,11 @@ Read **[Extracting State Logic into a Reducer](/learn/extracting-state-logic-int -## Passing data deeply with context {/*passing-data-deeply-with-context*/} +## Passing data deeply with Context {/*passing-data-deeply-with-context*/} Usually, you will pass information from a parent component to a child component via props. But passing props can become inconvenient if you need to pass some prop through many components, or if many components need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep it is—without passing it explicitly through props. -Here, the `Heading` component determines its heading level by "asking" the closest `Section` for its level. Each `Section` tracks its own level by asking the parent `Section` and adding one to it. Every `Section` provides information to all components below it without passing props--it does that through context. +Here, the `Heading` component determines its heading level by "asking" the closest `Section` for its level. Each `Section` tracks its own level by asking the parent `Section` and adding one to it. Every `Section` provides information to all components below it without passing props--it does that through Context. @@ -795,15 +795,15 @@ export const LevelContext = createContext(0); -Read **[Passing Data Deeply with Context](/learn/passing-data-deeply-with-context)** to learn about using context as an alternative to passing props. +Read **[Passing Data Deeply with Context](/learn/passing-data-deeply-with-context)** to learn about using Context as an alternative to passing props. -## Scaling up with reducer and context {/*scaling-up-with-reducer-and-context*/} +## Scaling up with reducer and Context {/*scaling-up-with-reducer-and-context*/} -Reducers let you consolidate a component’s state update logic. Context lets you pass information deep down to other components. You can combine reducers and context together to manage state of a complex screen. +Reducers let you consolidate a component’s state update logic. Context lets you pass information deep down to other components. You can combine reducers and Context together to manage state of a complex screen. -With this approach, a parent component with complex state manages it with a reducer. Other components anywhere deep in the tree can read its state via context. They can also dispatch actions to update that state. +With this approach, a parent component with complex state manages it with a reducer. Other components anywhere deep in the tree can read its state via Context. They can also dispatch actions to update that state. diff --git a/src/content/learn/passing-data-deeply-with-context.md b/src/content/learn/passing-data-deeply-with-context.md index 1aea87b354f..efbe1358636 100644 --- a/src/content/learn/passing-data-deeply-with-context.md +++ b/src/content/learn/passing-data-deeply-with-context.md @@ -11,9 +11,9 @@ Usually, you will pass information from a parent component to a child component - What "prop drilling" is -- How to replace repetitive prop passing with context -- Common use cases for context -- Common alternatives to context +- How to replace repetitive prop passing with Context +- Common use cases for Context +- Common alternatives to Context @@ -38,11 +38,11 @@ Prop drilling -Wouldn't it be great if there were a way to "teleport" data to the components in the tree that need it without passing props? With React's context feature, there is! +Wouldn't it be great if there were a way to "teleport" data to the components in the tree that need it without passing props? With React's Context feature, there is! ## Context: an alternative to passing props {/*context-an-alternative-to-passing-props*/} -Context lets a parent component provide data to the entire tree below it. There are many uses for context. Here is one example. Consider this `Heading` component that accepts a `level` for its size: +Context lets a parent component provide data to the entire tree below it. There are many uses for Context. Here is one example. Consider this `Heading` component that accepts a `level` for its size: @@ -202,11 +202,11 @@ It would be nice if you could pass the `level` prop to the `
` component But how can the `` component know the level of its closest `
`? **That would require some way for a child to "ask" for data from somewhere above in the tree.** -You can't do it with props alone. This is where context comes into play. You will do it in three steps: +You can't do it with props alone. This is where Context comes into play. You will do it in three steps: -1. **Create** a context. (You can call it `LevelContext`, since it's for the heading level.) -2. **Use** that context from the component that needs the data. (`Heading` will use `LevelContext`.) -3. **Provide** that context from the component that specifies the data. (`Section` will provide `LevelContext`.) +1. **Create** a Context. (You can call it `LevelContext`, since it's for the heading level.) +2. **Use** that Context from the component that needs the data. (`Heading` will use `LevelContext`.) +3. **Provide** that Context from the component that specifies the data. (`Section` will provide `LevelContext`.) Context lets a parent--even a distant one!--provide some data to the entire tree inside of it. @@ -214,21 +214,21 @@ Context lets a parent--even a distant one!--provide some data to the entire tree -Using context in close children +Using Context in close children -Using context in distant children +Using Context in distant children -### Step 1: Create the context {/*step-1-create-the-context*/} +### Step 1: Create the Context {/*step-1-create-the-context*/} -First, you need to create the context. You'll need to **export it from a file** so that your components can use it: +First, you need to create the Context. You'll need to **export it from a file** so that your components can use it: @@ -442,11 +442,11 @@ export const LevelContext = createContext(1); -Notice this example doesn't quite work, yet! All the headings have the same size because **even though you're *using* the context, you have not *provided* it yet.** React doesn't know where to get it! +Notice this example doesn't quite work, yet! All the headings have the same size because **even though you're *using* the Context, you have not *provided* it yet.** React doesn't know where to get it! -If you don't provide the context, React will use the default value you've specified in the previous step. In this example, you specified `1` as the argument to `createContext`, so `useContext(LevelContext)` returns `1`, setting all those headings to `

`. Let's fix this problem by having each `Section` provide its own context. +If you don't provide the Context, React will use the default value you've specified in the previous step. In this example, you specified `1` as the argument to `createContext`, so `useContext(LevelContext)` returns `1`, setting all those headings to `

`. Let's fix this problem by having each `Section` provide its own Context. -### Step 3: Provide the context {/*step-3-provide-the-context*/} +### Step 3: Provide the Context {/*step-3-provide-the-context*/} The `Section` component currently renders its children: @@ -460,7 +460,7 @@ export default function Section({ children }) { } ``` -**Wrap them with a context provider** to provide the `LevelContext` to them: +**Wrap them with a Context provider** to provide the `LevelContext` to them: ```js {1,6,8} import { LevelContext } from './LevelContext.js'; @@ -570,7 +570,7 @@ It's the same result as the original code, but you did not need to pass the `lev 2. `Section` wraps its children into ``. 3. `Heading` asks the closest value of `LevelContext` above with `useContext(LevelContext)`. -## Using and providing context from the same component {/*using-and-providing-context-from-the-same-component*/} +## Using and providing Context from the same component {/*using-and-providing-context-from-the-same-component*/} Currently, you still have to specify each section's `level` manually: @@ -585,7 +585,7 @@ export default function Page() { ... ``` -Since context lets you read information from a component above, each `Section` could read the `level` from the `Section` above, and pass `level + 1` down automatically. Here is how you could do it: +Since Context lets you read information from a component above, each `Section` could read the `level` from the `Section` above, and pass `level + 1` down automatically. Here is how you could do it: ```js src/Section.js {5,8} import { useContext } from 'react'; @@ -699,13 +699,13 @@ Now both `Heading` and `Section` read the `LevelContext` to figure out how "deep -This example uses heading levels because they show visually how nested components can override context. But context is useful for many other use cases too. You can pass down any information needed by the entire subtree: the current color theme, the currently logged in user, and so on. +This example uses heading levels because they show visually how nested components can override Context. But Context is useful for many other use cases too. You can pass down any information needed by the entire subtree: the current color theme, the currently logged in user, and so on. ## Context passes through intermediate components {/*context-passes-through-intermediate-components*/} -You can insert as many components as you like between the component that provides context and the one that uses it. This includes both built-in components like `
` and components you might build yourself. +You can insert as many components as you like between the component that provides Context and the one that uses it. This includes both built-in components like `
` and components you might build yourself. In this example, the same `Post` component (with a dashed border) is rendered at two different nesting levels. Notice that the `` inside of it gets its level automatically from the closest `
`: @@ -836,54 +836,54 @@ You didn't do anything special for this to work. A `Section` specifies the conte **Context lets you write components that "adapt to their surroundings" and display themselves differently depending on _where_ (or, in other words, _in which context_) they are being rendered.** -How context works might remind you of [CSS property inheritance.](https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance) In CSS, you can specify `color: blue` for a `
`, and any DOM node inside of it, no matter how deep, will inherit that color unless some other DOM node in the middle overrides it with `color: green`. Similarly, in React, the only way to override some context coming from above is to wrap children into a context provider with a different value. +How Context works might remind you of [CSS property inheritance.](https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance) In CSS, you can specify `color: blue` for a `
`, and any DOM node inside of it, no matter how deep, will inherit that color unless some other DOM node in the middle overrides it with `color: green`. Similarly, in React, the only way to override some Context coming from above is to wrap children into a Context provider with a different value. -In CSS, different properties like `color` and `background-color` don't override each other. You can set all `
`'s `color` to red without impacting `background-color`. Similarly, **different React contexts don't override each other.** Each context that you make with `createContext()` is completely separate from other ones, and ties together components using and providing *that particular* context. One component may use or provide many different contexts without a problem. +In CSS, different properties like `color` and `background-color` don't override each other. You can set all `
`'s `color` to red without impacting `background-color`. Similarly, **different React Contexts don't override each other.** Each Context that you make with `createContext()` is completely separate from other ones, and ties together components using and providing *that particular* Context. One component may use or provide many different Contexts without a problem. -## Before you use context {/*before-you-use-context*/} +## Before you use Context {/*before-you-use-context*/} -Context is very tempting to use! However, this also means it's too easy to overuse it. **Just because you need to pass some props several levels deep doesn't mean you should put that information into context.** +Context is very tempting to use! However, this also means it's too easy to overuse it. **Just because you need to pass some props several levels deep doesn't mean you should put that information into Context.** -Here's a few alternatives you should consider before using context: +Here's a few alternatives you should consider before using Context: 1. **Start by [passing props.](/learn/passing-props-to-a-component)** If your components are not trivial, it's not unusual to pass a dozen props down through a dozen components. It may feel like a slog, but it makes it very clear which components use which data! The person maintaining your code will be glad you've made the data flow explicit with props. 2. **Extract components and [pass JSX as `children`](/learn/passing-props-to-a-component#passing-jsx-as-children) to them.** If you pass some data through many layers of intermediate components that don't use that data (and only pass it further down), this often means that you forgot to extract some components along the way. For example, maybe you pass data props like `posts` to visual components that don't use them directly, like ``. Instead, make `Layout` take `children` as a prop, and render ``. This reduces the number of layers between the component specifying the data and the one that needs it. -If neither of these approaches works well for you, consider context. +If neither of these approaches works well for you, consider Context. -## Use cases for context {/*use-cases-for-context*/} +## Use cases for Context {/*use-cases-for-context*/} -* **Theming:** If your app lets the user change its appearance (e.g. dark mode), you can put a context provider at the top of your app, and use that context in components that need to adjust their visual look. -* **Current account:** Many components might need to know the currently logged in user. Putting it in context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value. -* **Routing:** Most routing solutions use context internally to hold the current route. This is how every link "knows" whether it's active or not. If you build your own router, you might want to do it too. -* **Managing state:** As your app grows, you might end up with a lot of state closer to the top of your app. Many distant components below may want to change it. It is common to [use a reducer together with context](/learn/scaling-up-with-reducer-and-context) to manage complex state and pass it down to distant components without too much hassle. +* **Theming:** If your app lets the user change its appearance (e.g. dark mode), you can put a Context provider at the top of your app, and use that Context in components that need to adjust their visual look. +* **Current account:** Many components might need to know the currently logged in user. Putting it in Context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value. +* **Routing:** Most routing solutions use Context internally to hold the current route. This is how every link "knows" whether it's active or not. If you build your own router, you might want to do it too. +* **Managing state:** As your app grows, you might end up with a lot of state closer to the top of your app. Many distant components below may want to change it. It is common to [use a reducer together with Context](/learn/scaling-up-with-reducer-and-context) to manage complex state and pass it down to distant components without too much hassle. Context is not limited to static values. If you pass a different value on the next render, React will update all the components reading it below! This is why context is often used in combination with state. -In general, if some information is needed by distant components in different parts of the tree, it's a good indication that context will help you. +In general, if some information is needed by distant components in different parts of the tree, it's a good indication that Context will help you. * Context lets a component provide some information to the entire tree below it. -* To pass context: +* To pass Context: 1. Create and export it with `export const MyContext = createContext(defaultValue)`. 2. Pass it to the `useContext(MyContext)` Hook to read it in any child component, no matter how deep. 3. Wrap children into `` to provide it from a parent. * Context passes through any components in the middle. * Context lets you write components that "adapt to their surroundings". -* Before you use context, try passing props or passing JSX as `children`. +* Before you use Context, try passing props or passing JSX as `children`. -#### Replace prop drilling with context {/*replace-prop-drilling-with-context*/} +#### Replace prop drilling with Context {/*replace-prop-drilling-with-context*/} In this example, toggling the checkbox changes the `imageSize` prop passed to each ``. The checkbox state is held in the top-level `App` component, but each `` needs to be aware of it. Currently, `App` passes `imageSize` to `List`, which passes it to each `Place`, which passes it to the `PlaceImage`. Remove the `imageSize` prop, and instead pass it from the `App` component directly to `PlaceImage`. -You can declare context in `Context.js`. +You can declare Context in `Context.js`. diff --git a/src/content/learn/rendering-lists.md b/src/content/learn/rendering-lists.md index 32f81c44707..aa9f98b5270 100644 --- a/src/content/learn/rendering-lists.md +++ b/src/content/learn/rendering-lists.md @@ -1082,7 +1082,7 @@ export const recipes = [{ Here, `` is a syntax shortcut saying "pass all properties of the `recipe` object as props to the `Recipe` component". You could also write each prop explicitly: ``. -**Note that the `key` is specified on the `` itself rather than on the root `
` returned from `Recipe`.** This is because this `key` is needed directly within the context of the surrounding array. Previously, you had an array of `
`s so each of them needed a `key`, but now you have an array of ``s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste. +**Note that the `key` is specified on the `` itself rather than on the root `
` returned from `Recipe`.** This is because this `key` is needed directly within the Context of the surrounding array. Previously, you had an array of `
`s so each of them needed a `key`, but now you have an array of ``s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste. diff --git a/src/content/learn/scaling-up-with-reducer-and-context.md b/src/content/learn/scaling-up-with-reducer-and-context.md index c3da0c6373d..2f574bf5b7b 100644 --- a/src/content/learn/scaling-up-with-reducer-and-context.md +++ b/src/content/learn/scaling-up-with-reducer-and-context.md @@ -4,19 +4,19 @@ title: Scaling Up with Reducer and Context -Reducers let you consolidate a component's state update logic. Context lets you pass information deep down to other components. You can combine reducers and context together to manage state of a complex screen. +Reducers let you consolidate a component's state update logic. Context lets you pass information deep down to other components. You can combine reducers and Context together to manage state of a complex screen. -* How to combine a reducer with context +* How to combine a reducer with Context * How to avoid passing state and dispatch through props -* How to keep context and state logic in a separate file +* How to keep Context and state logic in a separate file -## Combining a reducer with context {/*combining-a-reducer-with-context*/} +## Combining a reducer with Context {/*combining-a-reducer-with-context*/} In this example from [the introduction to reducers](/learn/extracting-state-logic-into-a-reducer), the state is managed by a reducer. The reducer function contains all of the state update logic and is declared at the bottom of this file: @@ -231,15 +231,15 @@ And `TaskList` passes the event handlers to `Task`: In a small example like this, this works well, but if you have tens or hundreds of components in the middle, passing down all state and functions can be quite frustrating! -This is why, as an alternative to passing them through props, you might want to put both the `tasks` state and the `dispatch` function [into context.](/learn/passing-data-deeply-with-context) **This way, any component below `TaskApp` in the tree can read the tasks and dispatch actions without the repetitive "prop drilling".** +This is why, as an alternative to passing them through props, you might want to put both the `tasks` state and the `dispatch` function [into Context.](/learn/passing-data-deeply-with-context) **This way, any component below `TaskApp` in the tree can read the tasks and dispatch actions without the repetitive "prop drilling".** -Here is how you can combine a reducer with context: +Here is how you can combine a reducer with Context: -1. **Create** the context. -2. **Put** state and dispatch into context. -3. **Use** context anywhere in the tree. +1. **Create** the Context. +2. **Put** state and dispatch into Context. +3. **Use** Context anywhere in the tree. -### Step 1: Create the context {/*step-1-create-the-context*/} +### Step 1: Create the Context {/*step-1-create-the-context*/} The `useReducer` Hook returns the current `tasks` and the `dispatch` function that lets you update them: @@ -247,7 +247,7 @@ The `useReducer` Hook returns the current `tasks` and the `dispatch` function th const [tasks, dispatch] = useReducer(tasksReducer, initialTasks); ``` -To pass them down the tree, you will [create](/learn/passing-data-deeply-with-context#step-2-use-the-context) two separate contexts: +To pass them down the tree, you will [create](/learn/passing-data-deeply-with-context#step-2-use-the-context) two separate Contexts: - `TasksContext` provides the current list of tasks. - `TasksDispatchContext` provides the function that lets components dispatch actions. @@ -448,11 +448,11 @@ ul, li { margin: 0; padding: 0; } -Here, you're passing `null` as the default value to both contexts. The actual values will be provided by the `TaskApp` component. +Here, you're passing `null` as the default value to both Contexts. The actual values will be provided by the `TaskApp` component. -### Step 2: Put state and dispatch into context {/*step-2-put-state-and-dispatch-into-context*/} +### Step 2: Put state and dispatch into Context {/*step-2-put-state-and-dispatch-into-context*/} -Now you can import both contexts in your `TaskApp` component. Take the `tasks` and `dispatch` returned by `useReducer()` and [provide them](/learn/passing-data-deeply-with-context#step-3-provide-the-context) to the entire tree below: +Now you can import both Contexts in your `TaskApp` component. Take the `tasks` and `dispatch` returned by `useReducer()` and [provide them](/learn/passing-data-deeply-with-context#step-3-provide-the-context) to the entire tree below: ```js {4,7-8} import { TasksContext, TasksDispatchContext } from './TasksContext.js'; @@ -470,7 +470,7 @@ export default function TaskApp() { } ``` -For now, you pass the information both via props and in context: +For now, you pass the information both via props and in Context: @@ -671,7 +671,7 @@ ul, li { margin: 0; padding: 0; } In the next step, you will remove prop passing. -### Step 3: Use context anywhere in the tree {/*step-3-use-context-anywhere-in-the-tree*/} +### Step 3: Use Context anywhere in the tree {/*step-3-use-context-anywhere-in-the-tree*/} Now you don't need to pass the list of tasks or the event handlers down the tree: @@ -693,7 +693,7 @@ export default function TaskList() { // ... ``` -To update the task list, any component can read the `dispatch` function from context and call it: +To update the task list, any component can read the `dispatch` function from Context and call it: ```js {3,9-13} export default function AddTask() { @@ -713,7 +713,7 @@ export default function AddTask() { // ... ``` -**The `TaskApp` component does not pass any event handlers down, and the `TaskList` does not pass any event handlers to the `Task` component either.** Each component reads the context that it needs: +**The `TaskApp` component does not pass any event handlers down, and the `TaskList` does not pass any event handlers to the `Task` component either.** Each component reads the Context that it needs: @@ -897,11 +897,11 @@ ul, li { margin: 0; padding: 0; } -**The state still "lives" in the top-level `TaskApp` component, managed with `useReducer`.** But its `tasks` and `dispatch` are now available to every component below in the tree by importing and using these contexts. +**The state still "lives" in the top-level `TaskApp` component, managed with `useReducer`.** But its `tasks` and `dispatch` are now available to every component below in the tree by importing and using these Contexts. ## Moving all wiring into a single file {/*moving-all-wiring-into-a-single-file*/} -You don't have to do this, but you could further declutter the components by moving both reducer and context into a single file. Currently, `TasksContext.js` contains only two context declarations: +You don't have to do this, but you could further declutter the components by moving both reducer and Context into a single file. Currently, `TasksContext.js` contains only two Context declarations: ```js import { createContext } from 'react'; @@ -913,7 +913,7 @@ export const TasksDispatchContext = createContext(null); This file is about to get crowded! You'll move the reducer into that same file. Then you'll declare a new `TasksProvider` component in the same file. This component will tie all the pieces together: 1. It will manage the state with a reducer. -2. It will provide both contexts to components below. +2. It will provide both Contexts to components below. 3. It will [take `children` as a prop](/learn/passing-props-to-a-component#passing-jsx-as-children) so you can pass JSX to it. ```js @@ -1121,7 +1121,7 @@ ul, li { margin: 0; padding: 0; } -You can also export functions that _use_ the context from `TasksContext.js`: +You can also export functions that _use_ the Context from `TasksContext.js`: ```js export function useTasks() { @@ -1133,14 +1133,14 @@ export function useTasksDispatch() { } ``` -When a component needs to read context, it can do it through these functions: +When a component needs to read Context, it can do it through these functions: ```js const tasks = useTasks(); const dispatch = useTasksDispatch(); ``` -This doesn't change the behavior in any way, but it lets you later split these contexts further or add some logic to these functions. **Now all of the context and reducer wiring is in `TasksContext.js`. This keeps the components clean and uncluttered, focused on what they display rather than where they get the data:** +This doesn't change the behavior in any way, but it lets you later split these Contexts further or add some logic to these functions. **Now all of the Context and reducer wiring is in `TasksContext.js`. This keeps the components clean and uncluttered, focused on what they display rather than where they get the data:** @@ -1352,13 +1352,13 @@ As your app grows, you may have many context-reducer pairs like this. This is a -- You can combine reducer with context to let any component read and update state above it. +- You can combine reducer with Context to let any component read and update state above it. - To provide state and the dispatch function to components below: - 1. Create two contexts (for state and for dispatch functions). - 2. Provide both contexts from the component that uses the reducer. - 3. Use either context from components that need to read them. + 1. Create two Contexts (for state and for dispatch functions). + 2. Provide both Contexts from the component that uses the reducer. + 3. Use either Context from components that need to read them. - You can further declutter the components by moving all wiring into one file. - - You can export a component like `TasksProvider` that provides context. + - You can export a component like `TasksProvider` that provides Context. - You can also export custom Hooks like `useTasks` and `useTasksDispatch` to read it. - You can have many context-reducer pairs like this in your app. diff --git a/src/content/learn/typescript.md b/src/content/learn/typescript.md index 6f49c76567c..02a8574b99f 100644 --- a/src/content/learn/typescript.md +++ b/src/content/learn/typescript.md @@ -244,7 +244,7 @@ export default function App() { The [`useContext` Hook](/reference/react/useContext) is a technique for passing data down the component tree without having to pass props through components. It is used by creating a provider component and often by creating a Hook to consume the value in a child component. -The type of the value provided by the context is inferred from the value passed to the `createContext` call: +The type of the value provided by the Context is inferred from the value passed to the `createContext` call: @@ -286,7 +286,7 @@ export default App = AppTSX; This technique works when you have a default value which makes sense - but there are occasionally cases when you do not, and in those cases `null` can feel reasonable as a default value. However, to allow the type-system to understand your code, you need to explicitly set `ContextShape | null` on the `createContext`. -This causes the issue that you need to eliminate the `| null` in the type for context consumers. Our recommendation is to have the Hook do a runtime check for it's existence and throw an error when not present: +This causes the issue that you need to eliminate the `| null` in the type for Context consumers. Our recommendation is to have the Hook do a runtime check for it's existence and throw an error when not present: ```js {5, 16-20} import { createContext, useContext, useState, useMemo } from 'react'; @@ -296,7 +296,7 @@ type ComplexObject = { kind: string }; -// The context is created with `| null` in the type, to accurately reflect the default value. +// The Context is created with `| null` in the type, to accurately reflect the default value. const Context = createContext(null); // The `| null` will be removed via the check in the Hook. diff --git a/src/content/reference/react-dom/createPortal.md b/src/content/reference/react-dom/createPortal.md index 0107c20d3e1..c5513041eb9 100644 --- a/src/content/reference/react-dom/createPortal.md +++ b/src/content/reference/react-dom/createPortal.md @@ -42,7 +42,7 @@ import { createPortal } from 'react-dom'; [See more examples below.](#usage) -A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events bubble up from children to parents according to the React tree. +A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the Context provided by the parent tree, and events bubble up from children to parents according to the React tree. #### Parameters {/*parameters*/} @@ -125,7 +125,7 @@ Notice how the second paragraph visually appears outside the parent `
` with ``` -A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events still bubble up from children to parents according to the React tree. +A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the Context provided by the parent tree, and events still bubble up from children to parents according to the React tree. --- diff --git a/src/content/reference/react-dom/preinit.md b/src/content/reference/react-dom/preinit.md index 3c9a879b4fd..42f3f09c4f5 100644 --- a/src/content/reference/react-dom/preinit.md +++ b/src/content/reference/react-dom/preinit.md @@ -68,7 +68,7 @@ The `preinit` function provides the browser with a hint that it should start dow * Multiple calls to `preinit` with the same `href` have the same effect as a single call. * In the browser, you can call `preinit` in any situation: while rendering a component, in an Effect, in an event handler, and so on. -* In server-side rendering or when rendering Server Components, `preinit` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. +* In server-side rendering or when rendering Server Components, `preinit` only has an effect if you call it while rendering a component or in an async ontext originating from rendering a component. Any other calls will be ignored. --- diff --git a/src/content/reference/react/Component.md b/src/content/reference/react/Component.md index 46406ff5e5d..c6b1f2f51c8 100644 --- a/src/content/reference/react/Component.md +++ b/src/content/reference/react/Component.md @@ -48,11 +48,11 @@ Only the `render` method is required, other methods are optional. --- -### `context` {/*context*/} +### `Context` {/*context*/} -The [context](/learn/passing-data-deeply-with-context) of a class component is available as `this.context`. It is only available if you specify *which* context you want to receive using [`static contextType`](#static-contexttype) (modern) or [`static contextTypes`](#static-contexttypes) (deprecated). +The [Context](/learn/passing-data-deeply-with-context) of a class component is available as `this.context`. It is only available if you specify *which* Context you want to receive using [`static contextType`](#static-contexttype) (modern) or [`static contextTypes`](#static-contexttypes) (deprecated). -A class component can only read one context at a time. +A class component can only read one Context at a time. ```js {2,5} class Button extends Component { diff --git a/src/content/reference/react/PureComponent.md b/src/content/reference/react/PureComponent.md index 3e2d074e10d..948e6a3b0ee 100644 --- a/src/content/reference/react/PureComponent.md +++ b/src/content/reference/react/PureComponent.md @@ -63,7 +63,7 @@ class Greeting extends PureComponent { } ``` -A React component should always have [pure rendering logic.](/learn/keeping-components-pure) This means that it must return the same output if its props, state, and context haven't changed. By using `PureComponent`, you are telling React that your component complies with this requirement, so React doesn't need to re-render as long as its props and state haven't changed. However, your component will still re-render if a context that it's using changes. +A React component should always have [pure rendering logic.](/learn/keeping-components-pure) This means that it must return the same output if its props, state, and Context haven't changed. By using `PureComponent`, you are telling React that your component complies with this requirement, so React doesn't need to re-render as long as its props and state haven't changed. However, your component will still re-render if a Context that it's using changes. In this example, notice that the `Greeting` component re-renders whenever `name` is changed (because that's one of its props), but not when `address` is changed (because it's not passed to `Greeting` as a prop): diff --git a/src/content/reference/react/StrictMode.md b/src/content/reference/react/StrictMode.md index 92c6ba63af0..4c628adf9be 100644 --- a/src/content/reference/react/StrictMode.md +++ b/src/content/reference/react/StrictMode.md @@ -124,7 +124,7 @@ In this example, Strict Mode checks will not run against the `Header` and `Foote ### Fixing bugs found by double rendering in development {/*fixing-bugs-found-by-double-rendering-in-development*/} -[React assumes that every component you write is a pure function.](/learn/keeping-components-pure) This means that React components you write must always return the same JSX given the same inputs (props, state, and context). +[React assumes that every component you write is a pure function.](/learn/keeping-components-pure) This means that React components you write must always return the same JSX given the same inputs (props, state, and Context). Components breaking this rule behave unpredictably and cause bugs. To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) **twice in development.** This includes: diff --git a/src/content/reference/react/apis.md b/src/content/reference/react/apis.md index 9c143787030..c0816c0ba9b 100644 --- a/src/content/reference/react/apis.md +++ b/src/content/reference/react/apis.md @@ -10,7 +10,7 @@ In addition to [Hooks](/reference/react) and [Components](/reference/react/compo --- -* [`createContext`](/reference/react/createContext) lets you define and provide context to the child components. Used with [`useContext`.](/reference/react/useContext) +* [`createContext`](/reference/react/createContext) lets you define and provide Context to the child components. Used with [`useContext`.](/reference/react/useContext) * [`forwardRef`](/reference/react/forwardRef) lets your component expose a DOM node as a ref to the parent. Used with [`useRef`.](/reference/react/useRef) * [`lazy`](/reference/react/lazy) lets you defer loading a component's code until it's rendered for the first time. * [`memo`](/reference/react/memo) lets your component skip re-renders with same props. Used with [`useMemo`](/reference/react/useMemo) and [`useCallback`.](/reference/react/useCallback) diff --git a/src/content/reference/react/cache.md b/src/content/reference/react/cache.md index 735560636a3..91bc5d33096 100644 --- a/src/content/reference/react/cache.md +++ b/src/content/reference/react/cache.md @@ -309,7 +309,7 @@ async function DemoProfile() { React only provides cache access to the memoized function in a component. When calling `getUser` outside of a component, it will still evaluate the function but not read or update the cache. -This is because cache access is provided through a [context](/learn/passing-data-deeply-with-context) which is only accessible from a component. +This is because cache access is provided through a [Context](/learn/passing-data-deeply-with-context) which is only accessible from a component. diff --git a/src/content/reference/react/cloneElement.md b/src/content/reference/react/cloneElement.md index 6bcea51b057..6f96bf716b6 100644 --- a/src/content/reference/react/cloneElement.md +++ b/src/content/reference/react/cloneElement.md @@ -393,9 +393,9 @@ This pattern is preferred to `cloneElement` because it is more explicit. --- -### Passing data through context {/*passing-data-through-context*/} +### Passing data through Context {/*passing-data-through-context*/} -Another alternative to `cloneElement` is to [pass data through context.](/learn/passing-data-deeply-with-context) +Another alternative to `cloneElement` is to [pass data through Context.](/learn/passing-data-deeply-with-context) For example, you can call [`createContext`](/reference/react/createContext) to define a `HighlightContext`: @@ -421,7 +421,7 @@ export default function List({ items, renderItem }) { })} ``` -With this approach, `Row` does not need to receive an `isHighlighted` prop at all. Instead, it reads the context: +With this approach, `Row` does not need to receive an `isHighlighted` prop at all. Instead, it reads the Context: ```js src/Row.js {2} export default function Row({ title }) { @@ -440,7 +440,7 @@ This allows the calling component to not know or worry about passing `isHighligh /> ``` -Instead, `List` and `Row` coordinate the highlighting logic through context. +Instead, `List` and `Row` coordinate the highlighting logic through Context. @@ -550,7 +550,7 @@ button { -[Learn more about passing data through context.](/reference/react/useContext#passing-data-deeply-into-the-tree) +[Learn more about passing data through Context.](/reference/react/useContext#passing-data-deeply-into-the-tree) --- diff --git a/src/content/reference/react/createContext.md b/src/content/reference/react/createContext.md index a653633c1d7..746e77be6aa 100644 --- a/src/content/reference/react/createContext.md +++ b/src/content/reference/react/createContext.md @@ -4,7 +4,7 @@ title: createContext -`createContext` lets you create a [context](/learn/passing-data-deeply-with-context) that components can provide or read. +`createContext` lets you create a [Context](/learn/passing-data-deeply-with-context) that components can provide or read. ```js const SomeContext = createContext(defaultValue) @@ -20,7 +20,7 @@ const SomeContext = createContext(defaultValue) ### `createContext(defaultValue)` {/*createcontext*/} -Call `createContext` outside of any components to create a context. +Call `createContext` outside of any components to create a Context. ```js import { createContext } from 'react'; @@ -32,22 +32,22 @@ const ThemeContext = createContext('light'); #### Parameters {/*parameters*/} -* `defaultValue`: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don't have any meaningful default value, specify `null`. The default value is meant as a "last resort" fallback. It is static and never changes over time. +* `defaultValue`: The value that you want the Context to have when there is no matching Context provider in the tree above the component that reads Context. If you don't have any meaningful default value, specify `null`. The default value is meant as a "last resort" fallback. It is static and never changes over time. #### Returns {/*returns*/} -`createContext` returns a context object. +`createContext` returns a Context object. -**The context object itself does not hold any information.** It represents _which_ context other components read or provide. Typically, you will use [`SomeContext.Provider`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/reference/react/useContext) in components below to read it. The context object has a few properties: +**The Context object itself does not hold any information.** It represents _which_ Context other components read or provide. Typically, you will use [`SomeContext.Provider`](#provider) in components above to specify the Context value, and call [`useContext(SomeContext)`](/reference/react/useContext) in components below to read it. The Context object has a few properties: -* `SomeContext.Provider` lets you provide the context value to components. -* `SomeContext.Consumer` is an alternative and rarely used way to read the context value. +* `SomeContext.Provider` lets you provide the Context value to components. +* `SomeContext.Consumer` is an alternative and rarely used way to read the Context value. --- ### `SomeContext.Provider` {/*provider*/} -Wrap your components into a context provider to specify the value of this context for all components inside: +Wrap your components into a Context provider to specify the value of this Context for all components inside: ```js function App() { @@ -63,13 +63,13 @@ function App() { #### Props {/*provider-props*/} -* `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/reference/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it. +* `value`: The value that you want to pass to all the components reading this Context inside this provider, no matter how deep. The Context value can be of any type. A component calling [`useContext(SomeContext)`](/reference/react/useContext) inside of the provider receives the `value` of the innermost corresponding Context provider above it. --- ### `SomeContext.Consumer` {/*consumer*/} -Before `useContext` existed, there was an older way to read context: +Before `useContext` existed, there was an older way to read Context: ```js function Button() { @@ -84,7 +84,7 @@ function Button() { } ``` -Although this older way still works, but **newly written code should read context with [`useContext()`](/reference/react/useContext) instead:** +Although this older way still works, but **newly written code should read Context with [`useContext()`](/reference/react/useContext) instead:** ```js function Button() { @@ -96,17 +96,17 @@ function Button() { #### Props {/*consumer-props*/} -* `children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](/reference/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context from the parent components changes. +* `children`: A function. React will call the function you pass with the current Context value determined by the same algorithm as [`useContext()`](/reference/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the Context from the parent components changes. --- ## Usage {/*usage*/} -### Creating context {/*creating-context*/} +### Creating Context {/*creating-context*/} Context lets components [pass information deep down](/learn/passing-data-deeply-with-context) without explicitly passing props. -Call `createContext` outside any components to create one or more contexts. +Call `createContext` outside any components to create one or more Contexts. ```js [[1, 3, "ThemeContext"], [1, 4, "AuthContext"], [3, 3, "'light'"], [3, 4, "null"]] import { createContext } from 'react'; @@ -115,7 +115,7 @@ const ThemeContext = createContext('light'); const AuthContext = createContext(null); ``` -`createContext` returns a context object. Components can read context by passing it to [`useContext()`](/reference/react/useContext): +`createContext` returns a Context object. Components can read Context by passing it to [`useContext()`](/reference/react/useContext): ```js [[1, 2, "ThemeContext"], [1, 7, "AuthContext"]] function Button() { @@ -129,7 +129,7 @@ function Profile() { } ``` -By default, the values they receive will be the default values you have specified when creating the contexts. However, by itself this isn't useful because the default values never change. +By default, the values they receive will be the default values you have specified when creating the Contexts. However, by itself this isn't useful because the default values never change. Context is useful because you can **provide other, dynamic values from your components:** @@ -150,15 +150,15 @@ function App() { } ``` -Now the `Page` component and any components inside it, no matter how deep, will "see" the passed context values. If the passed context values change, React will re-render the components reading the context as well. +Now the `Page` component and any components inside it, no matter how deep, will "see" the passed Context values. If the passed Context values change, React will re-render the components reading the Context as well. -[Read more about reading and providing context and see examples.](/reference/react/useContext) +[Read more about reading and providing Context and see examples.](/reference/react/useContext) --- -### Importing and exporting context from a file {/*importing-and-exporting-context-from-a-file*/} +### Importing and exporting Context from a file {/*importing-and-exporting-context-from-a-file*/} -Often, components in different files will need access to the same context. This is why it's common to declare contexts in a separate file. Then you can use the [`export` statement](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to make context available for other files: +Often, components in different files will need access to the same Context. This is why it's common to declare Contexts in a separate file. Then you can use the [`export` statement](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to make Context available for other files: ```js {4-5} // Contexts.js @@ -168,7 +168,7 @@ export const ThemeContext = createContext('light'); export const AuthContext = createContext(null); ``` -Components declared in other files can then use the [`import`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import) statement to read or provide this context: +Components declared in other files can then use the [`import`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import) statement to read or provide this Context: ```js {2} // Button.js @@ -202,10 +202,10 @@ This works similar to [importing and exporting components.](/learn/importing-and ## Troubleshooting {/*troubleshooting*/} -### I can't find a way to change the context value {/*i-cant-find-a-way-to-change-the-context-value*/} +### I can't find a way to change the Context value {/*i-cant-find-a-way-to-change-the-context-value*/} -Code like this specifies the *default* context value: +Code like this specifies the *default* Context value: ```js const ThemeContext = createContext('light'); @@ -213,5 +213,5 @@ const ThemeContext = createContext('light'); This value never changes. React only uses this value as a fallback if it can't find a matching provider above. -To make context change over time, [add state and wrap components in a context provider.](/reference/react/useContext#updating-data-passed-via-context) +To make Context change over time, [add state and wrap components in a context provider.](/reference/react/useContext#updating-data-passed-via-context) diff --git a/src/content/reference/react/hooks.md b/src/content/reference/react/hooks.md index cec71ce8f63..32079603e0f 100644 --- a/src/content/reference/react/hooks.md +++ b/src/content/reference/react/hooks.md @@ -31,7 +31,7 @@ function ImageGallery() { *Context* lets a component [receive information from distant parents without passing it as props.](/learn/passing-props-to-a-component) For example, your app's top-level component can pass the current UI theme to all components below, no matter how deep. -* [`useContext`](/reference/react/useContext) reads and subscribes to a context. +* [`useContext`](/reference/react/useContext) reads and subscribes to a Context. ```js function Button() { @@ -108,11 +108,11 @@ To prioritize rendering, use one of these Hooks: ## Resource Hooks {/*resource-hooks*/} -*Resources* can be accessed by a component without having them as part of their state. For example, a component can read a message from a Promise or read styling information from a context. +*Resources* can be accessed by a component without having them as part of their state. For example, a component can read a message from a Promise or read styling information from a Context. To read a value from a resource, use this Hook: -- [`use`](/reference/react/use) lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context). +- [`use`](/reference/react/use) lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [Context](/learn/passing-data-deeply-with-context). ```js function MessageComponent({ messagePromise }) { diff --git a/src/content/reference/react/memo.md b/src/content/reference/react/memo.md index 26fa9ed9cc6..e763efd7338 100644 --- a/src/content/reference/react/memo.md +++ b/src/content/reference/react/memo.md @@ -60,7 +60,7 @@ const Greeting = memo(function Greeting({ name }) { export default Greeting; ``` -A React component should always have [pure rendering logic.](/learn/keeping-components-pure) This means that it must return the same output if its props, state, and context haven't changed. By using `memo`, you are telling React that your component complies with this requirement, so React doesn't need to re-render as long as its props haven't changed. Even with `memo`, your component will re-render if its own state changes or if a context that it's using changes. +A React component should always have [pure rendering logic.](/learn/keeping-components-pure) This means that it must return the same output if its props, state, and Context haven't changed. By using `memo`, you are telling React that your component complies with this requirement, so React doesn't need to re-render as long as its props haven't changed. Even with `memo`, your component will re-render if its own state changes or if a Context that it's using changes. In this example, notice that the `Greeting` component re-renders whenever `name` is changed (because that's one of its props), but not when `address` is changed (because it's not passed to `Greeting` as a prop): @@ -207,9 +207,9 @@ If you set a state variable to its current value, React will skip re-rendering y --- -### Updating a memoized component using a context {/*updating-a-memoized-component-using-a-context*/} +### Updating a memoized component using a Context {/*updating-a-memoized-component-using-a-context*/} -Even when a component is memoized, it will still re-render when a context that it's using changes. Memoization only has to do with props that are passed to the component from its parent. +Even when a component is memoized, it will still re-render when a Context that it's using changes. Memoization only has to do with props that are passed to the component from its parent. @@ -263,7 +263,7 @@ label { -To make your component re-render only when a _part_ of some context changes, split your component in two. Read what you need from the context in the outer component, and pass it down to a memoized child as a prop. +To make your component re-render only when a _part_ of some Context changes, split your component in two. Read what you need from the Context in the outer component, and pass it down to a memoized child as a prop. --- diff --git a/src/content/reference/react/use.md b/src/content/reference/react/use.md index c3c8c92d2b3..3c8f7f9344a 100644 --- a/src/content/reference/react/use.md +++ b/src/content/reference/react/use.md @@ -11,7 +11,7 @@ The `use` Hook is currently only available in React's Canary and experimental ch -`use` is a React Hook that lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context). +`use` is a React Hook that lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [Context](/learn/passing-data-deeply-with-context). ```js const value = use(resource); @@ -27,7 +27,7 @@ const value = use(resource); ### `use(resource)` {/*use*/} -Call `use` in your component to read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context). +Call `use` in your component to read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [Context](/learn/passing-data-deeply-with-context). ```jsx import { use } from 'react'; @@ -46,11 +46,11 @@ When called with a Promise, the `use` Hook integrates with [`Suspense`](/referen #### Parameters {/*parameters*/} -* `resource`: this is the source of the data you want to read a value from. A resource can be a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a [context](/learn/passing-data-deeply-with-context). +* `resource`: this is the source of the data you want to read a value from. A resource can be a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a [Context](/learn/passing-data-deeply-with-context). #### Returns {/*returns*/} -The `use` Hook returns the value that was read from the resource like the resolved value of a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context). +The `use` Hook returns the value that was read from the resource like the resolved value of a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [Context](/learn/passing-data-deeply-with-context). #### Caveats {/*caveats*/} @@ -62,9 +62,9 @@ The `use` Hook returns the value that was read from the resource like the resolv ## Usage {/*usage*/} -### Reading context with `use` {/*reading-context-with-use*/} +### Reading Context with `use` {/*reading-context-with-use*/} -When a [context](/learn/passing-data-deeply-with-context) is passed to `use`, it works similarly to [`useContext`](/reference/react/useContext). While `useContext` must be called at the top level of your component, `use` can be called inside conditionals like `if` and loops like `for`. `use` is preferred over `useContext` because it is more flexible. +When a [Context](/learn/passing-data-deeply-with-context) is passed to `use`, it works similarly to [`useContext`](/reference/react/useContext). While `useContext` must be called at the top level of your component, `use` can be called inside conditionals like `if` and loops like `for`. `use` is preferred over `useContext` because it is more flexible. ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { use } from 'react'; @@ -74,9 +74,9 @@ function Button() { // ... ``` -`use` returns the context value for the context you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context. +`use` returns the Context value for the Context you passed. To determine the Context value, React searches the component tree and finds **the closest Context provider above** for that particular Context. -To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider. +To pass Context to a `Button`, wrap it or one of its parent components into the corresponding Context provider. ```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]] function MyPage() { @@ -110,7 +110,7 @@ function HorizontalRule({ show }) { -Like `useContext`, `use(context)` always looks for the closest context provider *above* the component that calls it. It searches upwards and **does not** consider context providers in the component from which you're calling `use(context)`. +Like `useContext`, `use(context)` always looks for the closest Context provider *above* the component that calls it. It searches upwards and **does not** consider Context providers in the component from which you're calling `use(context)`. diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md index ce06e7035d6..14d14fbce38 100644 --- a/src/content/reference/react/useContext.md +++ b/src/content/reference/react/useContext.md @@ -4,7 +4,7 @@ title: useContext -`useContext` is a React Hook that lets you read and subscribe to [context](/learn/passing-data-deeply-with-context) from your component. +`useContext` is a React Hook that lets you read and subscribe to [Context](/learn/passing-data-deeply-with-context) from your component. ```js const value = useContext(SomeContext) @@ -20,7 +20,7 @@ const value = useContext(SomeContext) ### `useContext(SomeContext)` {/*usecontext*/} -Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context) +Call `useContext` at the top level of your component to read and subscribe to [Context.](/learn/passing-data-deeply-with-context) ```js import { useContext } from 'react'; @@ -34,17 +34,17 @@ function MyComponent() { #### Parameters {/*parameters*/} -* `SomeContext`: The context that you've previously created with [`createContext`](/reference/react/createContext). The context itself does not hold the information, it only represents the kind of information you can provide or read from components. +* `SomeContext`: The Context that you've previously created with [`createContext`](/reference/react/createContext). The Context itself does not hold the information, it only represents the kind of information you can provide or read from components. #### Returns {/*returns*/} -`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/reference/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes. +`useContext` returns the Context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/reference/react/createContext) for that Context. The returned value is always up-to-date. React automatically re-renders components that read some Context if it changes. #### Caveats {/*caveats*/} * `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `` **needs to be *above*** the component doing the `useContext()` call. -* React **automatically re-renders** all the children that use a particular context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](/reference/react/memo) does not prevent the children receiving fresh context values. -* If your build system produces duplicates modules in the output (which can happen with symlinks), this can break context. Passing something via context only works if `SomeContext` that you use to provide context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison. +* React **automatically re-renders** all the children that use a particular Context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](/reference/react/memo) does not prevent the children receiving fresh Context values. +* If your build system produces duplicates modules in the output (which can happen with symlinks), this can break Context. Passing something via Context only works if `SomeContext` that you use to provide Context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison. --- @@ -53,7 +53,7 @@ function MyComponent() { ### Passing data deeply into the tree {/*passing-data-deeply-into-the-tree*/} -Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context) +Call `useContext` at the top level of your component to read and subscribe to [Context.](/learn/passing-data-deeply-with-context) ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { useContext } from 'react'; @@ -63,9 +63,9 @@ function Button() { // ... ``` -`useContext` returns the context value for the context you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context. +`useContext` returns the Context value for the Context you passed. To determine the Context value, React searches the component tree and finds **the closest Context provider above** for that particular Context. -To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider: +To pass Context to a `Button`, wrap it or one of its parent components into the corresponding Context provider: ```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]] function MyPage() { @@ -175,9 +175,9 @@ function Button({ children }) { --- -### Updating data passed via context {/*updating-data-passed-via-context*/} +### Updating data passed via Context {/*updating-data-passed-via-context*/} -Often, you'll want the context to change over time. To update context, combine it with [state.](/reference/react/useState) Declare a state variable in the parent component, and pass the current state down as the context value to the provider. +Often, you'll want the Context to change over time. To update Context, combine it with [state.](/reference/react/useState) Declare a state variable in the parent component, and pass the current state down as the Context value to the provider. ```js {2} [[1, 4, "ThemeContext"], [2, 4, "theme"], [1, 11, "ThemeContext"]] function MyPage() { @@ -197,11 +197,11 @@ function MyPage() { Now any `Button` inside of the provider will receive the current `theme` value. If you call `setTheme` to update the `theme` value that you pass to the provider, all `Button` components will re-render with the new `'light'` value. - + -#### Updating a value via context {/*updating-a-value-via-context*/} +#### Updating a value via Context {/*updating-a-value-via-context*/} -In this example, the `MyApp` component holds a state variable which is then passed to the `ThemeContext` provider. Checking the "Dark mode" checkbox updates the state. Changing the provided value re-renders all the components using that context. +In this example, the `MyApp` component holds a state variable which is then passed to the `ThemeContext` provider. Checking the "Dark mode" checkbox updates the state. Changing the provided value re-renders all the components using that Context. @@ -299,13 +299,13 @@ function Button({ children }) { -Note that `value="dark"` passes the `"dark"` string, but `value={theme}` passes the value of the JavaScript `theme` variable with [JSX curly braces.](/learn/javascript-in-jsx-with-curly-braces) Curly braces also let you pass context values that aren't strings. +Note that `value="dark"` passes the `"dark"` string, but `value={theme}` passes the value of the JavaScript `theme` variable with [JSX curly braces.](/learn/javascript-in-jsx-with-curly-braces) Curly braces also let you pass Context values that aren't strings. -#### Updating an object via context {/*updating-an-object-via-context*/} +#### Updating an object via Context {/*updating-an-object-via-context*/} -In this example, there is a `currentUser` state variable which holds an object. You combine `{ currentUser, setCurrentUser }` into a single object and pass it down through the context inside the `value={}`. This lets any component below, such as `LoginButton`, read both `currentUser` and `setCurrentUser`, and then call `setCurrentUser` when needed. +In this example, there is a `currentUser` state variable which holds an object. You combine `{ currentUser, setCurrentUser }` into a single object and pass it down through the Context inside the `value={}`. This lets any component below, such as `LoginButton`, read both `currentUser` and `setCurrentUser`, and then call `setCurrentUser` when needed. @@ -395,9 +395,9 @@ label { -#### Multiple contexts {/*multiple-contexts*/} +#### Multiple Contexts {/*multiple-contexts*/} -In this example, there are two independent contexts. `ThemeContext` provides the current theme, which is a string, while `CurrentUserContext` holds the object representing the current user. +In this example, there are two independent Contexts. `ThemeContext` provides the current theme, which is a string, while `CurrentUserContext` holds the object representing the current user. @@ -564,7 +564,7 @@ label { #### Extracting providers to a component {/*extracting-providers-to-a-component*/} -As your app grows, it is expected that you'll have a "pyramid" of contexts closer to the root of your app. There is nothing wrong with that. However, if you dislike the nesting aesthetically, you can extract the providers into a single component. In this example, `MyProviders` hides the "plumbing" and renders the children passed to it inside the necessary providers. Note that the `theme` and `setTheme` state is needed in `MyApp` itself, so `MyApp` still owns that piece of the state. +As your app grows, it is expected that you'll have a "pyramid" of Contexts closer to the root of your app. There is nothing wrong with that. However, if you dislike the nesting aesthetically, you can extract the providers into a single component. In this example, `MyProviders` hides the "plumbing" and renders the children passed to it inside the necessary providers. Note that the `theme` and `setTheme` state is needed in `MyApp` itself, so `MyApp` still owns that piece of the state. @@ -737,9 +737,9 @@ label { -#### Scaling up with context and a reducer {/*scaling-up-with-context-and-a-reducer*/} +#### Scaling up with Context and a reducer {/*scaling-up-with-context-and-a-reducer*/} -In larger apps, it is common to combine context with a [reducer](/reference/react/useReducer) to extract the logic related to some state out of components. In this example, all the "wiring" is hidden in the `TasksContext.js`, which contains a reducer and two separate contexts. +In larger apps, it is common to combine Context with a [reducer](/reference/react/useReducer) to extract the logic related to some state out of components. In this example, all the "wiring" is hidden in the `TasksContext.js`, which contains a reducer and two separate Contexts. Read a [full walkthrough](/learn/scaling-up-with-reducer-and-context) of this example. @@ -949,13 +949,13 @@ ul, li { margin: 0; padding: 0; } ### Specifying a fallback default value {/*specifying-a-fallback-default-value*/} -If React can't find any providers of that particular context in the parent tree, the context value returned by `useContext()` will be equal to the default value that you specified when you [created that context](/reference/react/createContext): +If React can't find any providers of that particular Context in the parent tree, the Context value returned by `useContext()` will be equal to the default value that you specified when you [created that Context](/reference/react/createContext): ```js [[1, 1, "ThemeContext"], [3, 1, "null"]] const ThemeContext = createContext(null); ``` -The default value **never changes**. If you want to update context, use it with state as [described above.](#updating-data-passed-via-context) +The default value **never changes**. If you want to update Context, use it with state as [described above.](#updating-data-passed-via-context) Often, instead of `null`, there is some more meaningful value you can use as a default, for example: @@ -965,7 +965,7 @@ const ThemeContext = createContext('light'); This way, if you accidentally render some component without a corresponding provider, it won't break. This also helps your components work well in a test environment without setting up a lot of providers in the tests. -In the example below, the "Toggle theme" button is always light because it's **outside any theme context provider** and the default context theme value is `'light'`. Try editing the default theme to be `'dark'`. +In the example below, the "Toggle theme" button is always light because it's **outside any theme Context provider** and the default Context theme value is `'light'`. Try editing the default theme to be `'dark'`. @@ -1062,9 +1062,9 @@ function Button({ children, onClick }) { --- -### Overriding context for a part of the tree {/*overriding-context-for-a-part-of-the-tree*/} +### Overriding Context for a part of the tree {/*overriding-context-for-a-part-of-the-tree*/} -You can override the context for a part of the tree by wrapping that part in a provider with a different value. +You can override the Context for a part of the tree by wrapping that part in a provider with a different value. ```js {3,5} @@ -1078,11 +1078,11 @@ You can override the context for a part of the tree by wrapping that part in a p You can nest and override providers as many times as you need. - + #### Overriding a theme {/*overriding-a-theme*/} -Here, the button *inside* the `Footer` receives a different context value (`"light"`) than the buttons outside (`"dark"`). +Here, the button *inside* the `Footer` receives a different Context value (`"light"`) than the buttons outside (`"dark"`). @@ -1188,7 +1188,7 @@ footer { #### Automatically nested headings {/*automatically-nested-headings*/} -You can "accumulate" information when you nest context providers. In this example, the `Section` component keeps track of the `LevelContext` which specifies the depth of the section nesting. It reads the `LevelContext` from the parent section, and provides the `LevelContext` number increased by one to its children. As a result, the `Heading` component can automatically decide which of the `

`, `

`, `

`, ..., tags to use based on how many `Section` components it is nested inside of. +You can "accumulate" information when you nest Context providers. In this example, the `Section` component keeps track of the `LevelContext` which specifies the depth of the section nesting. It reads the `LevelContext` from the parent section, and provides the `LevelContext` number increased by one to its children. As a result, the `Heading` component can automatically decide which of the `

`, `

`, `

`, ..., tags to use based on how many `Section` components it is nested inside of. Read a [detailed walkthrough](/learn/passing-data-deeply-with-context) of this example. @@ -1290,7 +1290,7 @@ export const LevelContext = createContext(0); ### Optimizing re-renders when passing objects and functions {/*optimizing-re-renders-when-passing-objects-and-functions*/} -You can pass any values via context, including objects and functions. +You can pass any values via Context, including objects and functions. ```js [[2, 10, "{ currentUser, login }"]] function MyApp() { @@ -1309,7 +1309,7 @@ function MyApp() { } ``` -Here, the context value is a JavaScript object with two properties, one of which is a function. Whenever `MyApp` re-renders (for example, on a route update), this will be a *different* object pointing at a *different* function, so React will also have to re-render all components deep in the tree that call `useContext(AuthContext)`. +Here, the Context value is a JavaScript object with two properties, one of which is a function. Whenever `MyApp` re-renders (for example, on a route update), this will be a *different* object pointing at a *different* function, so React will also have to re-render all components deep in the tree that call `useContext(AuthContext)`. In smaller apps, this is not a problem. However, there is no need to re-render them if the underlying data, like `currentUser`, has not changed. To help React take advantage of that fact, you may wrap the `login` function with [`useCallback`](/reference/react/useCallback) and wrap the object creation into [`useMemo`](/reference/react/useMemo). This is a performance optimization: @@ -1353,7 +1353,7 @@ There are a few common ways that this can happen: 2. You may have forgotten to wrap your component with ``, or you might have put it in a different part of the tree than you thought. Check whether the hierarchy is right using [React DevTools.](/learn/react-developer-tools) 3. You might be running into some build issue with your tooling that causes `SomeContext` as seen from the providing component and `SomeContext` as seen by the reading component to be two different objects. This can happen if you use symlinks, for example. You can verify this by assigning them to globals like `window.SomeContext1` and `window.SomeContext2` and then checking whether `window.SomeContext1 === window.SomeContext2` in the console. If they're not the same, fix that issue on the build tool level. -### I am always getting `undefined` from my context although the default value is different {/*i-am-always-getting-undefined-from-my-context-although-the-default-value-is-different*/} +### I am always getting `undefined` from my Context although the default value is different {/*i-am-always-getting-undefined-from-my-context-although-the-default-value-is-different*/} You might have a provider without a `value` in the tree: @@ -1384,4 +1384,4 @@ In both of these cases you should see a warning from React in the console. To fi ``` -Note that the [default value from your `createContext(defaultValue)` call](#specifying-a-fallback-default-value) is only used **if there is no matching provider above at all.** If there is a `` component somewhere in the parent tree, the component calling `useContext(SomeContext)` *will* receive `undefined` as the context value. +Note that the [default value from your `createContext(defaultValue)` call](#specifying-a-fallback-default-value) is only used **if there is no matching provider above at all.** If there is a `` component somewhere in the parent tree, the component calling `useContext(SomeContext)` *will* receive `undefined` as the Context value. diff --git a/src/content/reference/react/useRef.md b/src/content/reference/react/useRef.md index fcecae7149b..5c0e5f08d08 100644 --- a/src/content/reference/react/useRef.md +++ b/src/content/reference/react/useRef.md @@ -192,7 +192,7 @@ export default function Stopwatch() { React expects that the body of your component [behaves like a pure function](/learn/keeping-components-pure): -- If the inputs ([props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [context](/learn/passing-data-deeply-with-context)) are the same, it should return exactly the same JSX. +- If the inputs ([props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [Context](/learn/passing-data-deeply-with-context)) are the same, it should return exactly the same JSX. - Calling it in a different order or with different arguments should not affect the results of other calls. Reading or writing a ref **during rendering** breaks these expectations. diff --git a/src/content/reference/react/useSyncExternalStore.md b/src/content/reference/react/useSyncExternalStore.md index 481690d7ed1..f487082b467 100644 --- a/src/content/reference/react/useSyncExternalStore.md +++ b/src/content/reference/react/useSyncExternalStore.md @@ -83,7 +83,7 @@ The current snapshot of the store which you can use in your rendering logic. ### Subscribing to an external store {/*subscribing-to-an-external-store*/} -Most of your React components will only read data from their [props,](/learn/passing-props-to-a-component) [state,](/reference/react/useState) and [context.](/reference/react/useContext) However, sometimes a component needs to read some data from some store outside of React that changes over time. This includes: +Most of your React components will only read data from their [props,](/learn/passing-props-to-a-component) [state,](/reference/react/useState) and [Context.](/reference/react/useContext) However, sometimes a component needs to read some data from some store outside of React that changes over time. This includes: * Third-party state management libraries that hold state outside of React. * Browser APIs that expose a mutable value and events to subscribe to its changes. diff --git a/src/content/reference/rules/components-and-hooks-must-be-pure.md b/src/content/reference/rules/components-and-hooks-must-be-pure.md index 3112ea03944..451d3189d4d 100644 --- a/src/content/reference/rules/components-and-hooks-must-be-pure.md +++ b/src/content/reference/rules/components-and-hooks-must-be-pure.md @@ -16,7 +16,7 @@ This reference page covers advanced topics and requires familiarity with the con One of the key concepts that makes React, _React_ is _purity_. A pure component or hook is one that is: -* **Idempotent** – You [always get the same result everytime](/learn/keeping-components-pure#purity-components-as-formulas) you run it with the same inputs – props, state, context for component inputs; and arguments for hook inputs. +* **Idempotent** – You [always get the same result everytime](/learn/keeping-components-pure#purity-components-as-formulas) you run it with the same inputs – props, state, Context for component inputs; and arguments for hook inputs. * **Has no side effects in render** – Code with side effects should run [**separately from rendering**](#how-does-react-run-your-code). For example as an [event handler](/learn/responding-to-events) – where the user interacts with the UI and causes it to update; or as an [Effect](/reference/react/useEffect) – which runs after render. * **Does not mutate non-local values**: Components and Hooks should [never modify values that aren't created locally](#mutation) in render. @@ -70,7 +70,7 @@ function Dropdown() { ## Components and Hooks must be idempotent {/*components-and-hooks-must-be-idempotent*/} -Components must always return the same output with respect to their inputs – props, state, and context. This is known as _idempotency_. [Idempotency](https://en.wikipedia.org/wiki/Idempotence) is a term popularized in functional programming. It refers to the idea that you [always get the same result everytime](learn/keeping-components-pure) you run that piece of code with the same inputs. +Components must always return the same output with respect to their inputs – props, state, and Context. This is known as _idempotency_. [Idempotency](https://en.wikipedia.org/wiki/Idempotence) is a term popularized in functional programming. It refers to the idea that you [always get the same result everytime](learn/keeping-components-pure) you run that piece of code with the same inputs. This means that _all_ code that runs [during render](#how-does-react-run-your-code) must also be idempotent in order for this rule to hold. For example, this line of code is not idempotent (and therefore, neither is the component): diff --git a/src/content/reference/rules/index.md b/src/content/reference/rules/index.md index dd5f7456c84..5d9ee9216ea 100644 --- a/src/content/reference/rules/index.md +++ b/src/content/reference/rules/index.md @@ -26,7 +26,7 @@ We strongly recommend using [Strict Mode](/reference/react/StrictMode) alongside [Purity in Components and Hooks](/reference/rules/components-and-hooks-must-be-pure) is a key rule of React that makes your app predictable, easy to debug, and allows React to automatically optimize your code. -* [Components must be idempotent](/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent) – React components are assumed to always return the same output with respect to their inputs – props, state, and context. +* [Components must be idempotent](/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent) – React components are assumed to always return the same output with respect to their inputs – props, state, and Context. * [Side effects must run outside of render](/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) – Side effects should not run in render, as React can render components multiple times to create the best possible user experience. * [Props and state are immutable](/reference/rules/components-and-hooks-must-be-pure#props-and-state-are-immutable) – A component’s props and state are immutable snapshots with respect to a single render. Never mutate them directly. * [Return values and arguments to Hooks are immutable](/reference/rules/components-and-hooks-must-be-pure#return-values-and-arguments-to-hooks-are-immutable) – Once values are passed to a Hook, you should not modify them. Like props in JSX, values become immutable when passed to a Hook. From 61a86872796a352895b7d437bdafec30198ecbf7 Mon Sep 17 00:00:00 2001 From: Dmitry Litsman Date: Wed, 27 Mar 2024 16:23:19 +0000 Subject: [PATCH 2/4] Revert blog changes for context -> Context change --- src/content/blog/2022/03/29/react-v18.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/blog/2022/03/29/react-v18.md b/src/content/blog/2022/03/29/react-v18.md index 64a08cf50c5..743404c1af9 100644 --- a/src/content/blog/2022/03/29/react-v18.md +++ b/src/content/blog/2022/03/29/react-v18.md @@ -285,7 +285,7 @@ See [How to Upgrade to React 18](/blog/2022/03/08/react-18-upgrade-guide) for st * Improve memory usage. ([#21039](https://github.com/facebook/react/pull/21039) by [@bgirard](https://github.com/bgirard)) * Improve messages if string coercion throws (Temporal.*, Symbol, etc.) ([#22064](https://github.com/facebook/react/pull/22064) by [@justingrant](https://github.com/justingrant)) * Use `setImmediate` when available over `MessageChannel`. ([#20834](https://github.com/facebook/react/pull/20834) by [@gaearon](https://github.com/gaearon)) -* Fix Context failing to propagate inside suspended trees. ([#23095](https://github.com/facebook/react/pull/23095) by [@gaearon](https://github.com/gaearon)) +* Fix context failing to propagate inside suspended trees. ([#23095](https://github.com/facebook/react/pull/23095) by [@gaearon](https://github.com/gaearon)) * Fix `useReducer` observing incorrect props by removing the eager bailout mechanism. ([#22445](https://github.com/facebook/react/pull/22445) by [@josephsavona](https://github.com/josephsavona)) * Fix `setState` being ignored in Safari when appending iframes. ([#23111](https://github.com/facebook/react/pull/23111) by [@gaearon](https://github.com/gaearon)) * Fix a crash when rendering `ZonedDateTime` in the tree. ([#20617](https://github.com/facebook/react/pull/20617) by [@dimaqq](https://github.com/dimaqq)) @@ -312,7 +312,7 @@ See [How to Upgrade to React 18](/blog/2022/03/08/react-18-upgrade-guide) for st ### React DOM Server {/*react-dom-server-1*/} * Add the new streaming renderer. ([#14144](https://github.com/facebook/react/pull/14144), [#20970](https://github.com/facebook/react/pull/20970), [#21056](https://github.com/facebook/react/pull/21056), [#21255](https://github.com/facebook/react/pull/21255), [#21200](https://github.com/facebook/react/pull/21200), [#21257](https://github.com/facebook/react/pull/21257), [#21276](https://github.com/facebook/react/pull/21276), [#22443](https://github.com/facebook/react/pull/22443), [#22450](https://github.com/facebook/react/pull/22450), [#23247](https://github.com/facebook/react/pull/23247), [#24025](https://github.com/facebook/react/pull/24025), [#24030](https://github.com/facebook/react/pull/24030) by [@sebmarkbage](https://github.com/sebmarkbage)) -* Fix Context providers in SSR when handling multiple requests. ([#23171](https://github.com/facebook/react/pull/23171) by [@frandiox](https://github.com/frandiox)) +* Fix context providers in SSR when handling multiple requests. ([#23171](https://github.com/facebook/react/pull/23171) by [@frandiox](https://github.com/frandiox)) * Revert to client render on text mismatch. ([#23354](https://github.com/facebook/react/pull/23354) by [@acdlite](https://github.com/acdlite)) * Deprecate `renderToNodeStream`. ([#23359](https://github.com/facebook/react/pull/23359) by [@sebmarkbage](https://github.com/sebmarkbage)) * Fix a spurious error log in the new server renderer. ([#24043](https://github.com/facebook/react/pull/24043) by [@eps1lon](https://github.com/eps1lon)) From e95309ce84f63c8ed758118259833d79f230d1f2 Mon Sep 17 00:00:00 2001 From: Dmitry Litsman Date: Wed, 27 Mar 2024 16:34:28 +0000 Subject: [PATCH 3/4] fixing some incorrect context changes --- src/content/learn/rendering-lists.md | 2 +- src/content/reference/react-dom/preinit.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/learn/rendering-lists.md b/src/content/learn/rendering-lists.md index aa9f98b5270..32f81c44707 100644 --- a/src/content/learn/rendering-lists.md +++ b/src/content/learn/rendering-lists.md @@ -1082,7 +1082,7 @@ export const recipes = [{ Here, `` is a syntax shortcut saying "pass all properties of the `recipe` object as props to the `Recipe` component". You could also write each prop explicitly: ``. -**Note that the `key` is specified on the `` itself rather than on the root `
` returned from `Recipe`.** This is because this `key` is needed directly within the Context of the surrounding array. Previously, you had an array of `
`s so each of them needed a `key`, but now you have an array of ``s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste. +**Note that the `key` is specified on the `` itself rather than on the root `
` returned from `Recipe`.** This is because this `key` is needed directly within the context of the surrounding array. Previously, you had an array of `
`s so each of them needed a `key`, but now you have an array of ``s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste. diff --git a/src/content/reference/react-dom/preinit.md b/src/content/reference/react-dom/preinit.md index 42f3f09c4f5..3c9a879b4fd 100644 --- a/src/content/reference/react-dom/preinit.md +++ b/src/content/reference/react-dom/preinit.md @@ -68,7 +68,7 @@ The `preinit` function provides the browser with a hint that it should start dow * Multiple calls to `preinit` with the same `href` have the same effect as a single call. * In the browser, you can call `preinit` in any situation: while rendering a component, in an Effect, in an event handler, and so on. -* In server-side rendering or when rendering Server Components, `preinit` only has an effect if you call it while rendering a component or in an async ontext originating from rendering a component. Any other calls will be ignored. +* In server-side rendering or when rendering Server Components, `preinit` only has an effect if you call it while rendering a component or in an async context originating from rendering a component. Any other calls will be ignored. --- From d91f320f468a57263cb17f57c87fefdfd409694c Mon Sep 17 00:00:00 2001 From: Dmitry Litsman Date: Sun, 14 Apr 2024 17:50:50 +0100 Subject: [PATCH 4/4] Update components-and-hooks-must-be-pure.md --- .../reference/rules/components-and-hooks-must-be-pure.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/reference/rules/components-and-hooks-must-be-pure.md b/src/content/reference/rules/components-and-hooks-must-be-pure.md index 733597c63b8..521eeb04d36 100644 --- a/src/content/reference/rules/components-and-hooks-must-be-pure.md +++ b/src/content/reference/rules/components-and-hooks-must-be-pure.md @@ -16,7 +16,7 @@ This reference page covers advanced topics and requires familiarity with the con One of the key concepts that makes React, _React_ is _purity_. A pure component or hook is one that is: -* **Idempotent** – You [always get the same result every time](/learn/keeping-components-pure#purity-components-as-formulas) you run it with the same inputs – props, state, context for component inputs; and arguments for hook inputs. +* **Idempotent** – You [always get the same result every time](/learn/keeping-components-pure#purity-components-as-formulas) you run it with the same inputs – props, state, Context for component inputs; and arguments for hook inputs. * **Has no side effects in render** – Code with side effects should run [**separately from rendering**](#how-does-react-run-your-code). For example as an [event handler](/learn/responding-to-events) – where the user interacts with the UI and causes it to update; or as an [Effect](/reference/react/useEffect) – which runs after render. * **Does not mutate non-local values**: Components and Hooks should [never modify values that aren't created locally](#mutation) in render. @@ -70,7 +70,7 @@ function Dropdown() { ## Components and Hooks must be idempotent {/*components-and-hooks-must-be-idempotent*/} -Components must always return the same output with respect to their inputs – props, state, and context. This is known as _idempotency_. [Idempotency](https://en.wikipedia.org/wiki/Idempotence) is a term popularized in functional programming. It refers to the idea that you [always get the same result every time](learn/keeping-components-pure) you run that piece of code with the same inputs. +Components must always return the same output with respect to their inputs – props, state, and Context. This is known as _idempotency_. [Idempotency](https://en.wikipedia.org/wiki/Idempotence) is a term popularized in functional programming. It refers to the idea that you [always get the same result every time](learn/keeping-components-pure) you run that piece of code with the same inputs. This means that _all_ code that runs [during render](#how-does-react-run-your-code) must also be idempotent in order for this rule to hold. For example, this line of code is not idempotent (and therefore, neither is the component):