diff --git a/src/content/learn/managing-state.md b/src/content/learn/managing-state.md index ef7b76e04c2..f31b75a6493 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 fead4056db5..95b6f06d27c 100644 --- a/src/content/learn/passing-data-deeply-with-context.md +++ b/src/content/learn/passing-data-deeply-with-context.md @@ -38,7 +38,7 @@ 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*/} @@ -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: @@ -310,9 +310,9 @@ export const LevelContext = createContext(1); The only argument to `createContext` is the _default_ value. Here, `1` refers to the biggest heading level, but you could pass any kind of value (even an object). You will see the significance of the default value in the next step. -### Step 2: Use the context {/*step-2-use-the-context*/} +### Step 2: Use the Context {/*step-2-use-the-context*/} -Import the `useContext` Hook from React and your context: +Import the `useContext` Hook from React and your Context: ```js import { useContext } from 'react'; @@ -327,7 +327,7 @@ export default function Heading({ level, children }) { } ``` -Instead, remove the `level` prop and read the value from the context you just imported, `LevelContext`: +Instead, remove the `level` prop and read the value from the Context you just imported, `LevelContext`: ```js {2} export default function Heading({ children }) { @@ -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 `
`: @@ -832,58 +832,58 @@ export const LevelContext = createContext(0); -You didn't do anything special for this to work. A `Section` specifies the context for the tree inside it, so you can insert a `` anywhere, and it will have the correct size. Try it in the sandbox above! +You didn't do anything special for this to work. A `Section` specifies the Context for the tree inside it, so you can insert a `` anywhere, and it will have the correct size. Try it in the sandbox above! **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. +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. 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/scaling-up-with-reducer-and-context.md b/src/content/learn/scaling-up-with-reducer-and-context.md index 01483bebf48..2d2a43906fb 100644 --- a/src/content/learn/scaling-up-with-reducer-and-context.md +++ b/src/content/learn/scaling-up-with-reducer-and-context.md @@ -233,13 +233,13 @@ In a small example like this, this works well, but if you have tens or hundreds 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'; @@ -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'; @@ -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:** @@ -1348,18 +1348,18 @@ Functions like `useTasks` and `useTasksDispatch` are called *[Custom Hooks.](/le -As your app grows, you may have many context-reducer pairs like this. This is a powerful way to scale your app and [lift state up](/learn/sharing-state-between-components) without too much work whenever you want to access the data deep in the tree. +As your app grows, you may have many Context-reducer pairs like this. This is a powerful way to scale your app and [lift state up](/learn/sharing-state-between-components) without too much work whenever you want to access the data deep in the tree. -- 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. +- 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 2e6f7edc53e..0567be60123 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 its 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/eslint-plugin-react-hooks/lints/globals.md b/src/content/reference/eslint-plugin-react-hooks/lints/globals.md index fe0cbe0080f..d54fe737822 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/globals.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/globals.md @@ -67,7 +67,7 @@ function Component() { ); } -// ✅ Use context for global values +// ✅ Use Context for global values function Component() { const user = useContext(UserContext); return
User: {user.id}
; diff --git a/src/content/reference/react-dom/createPortal.md b/src/content/reference/react-dom/createPortal.md index e806660e869..52eeff08710 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/Component.md b/src/content/reference/react/Component.md index f6c8cc4bf32..47978925544 100644 --- a/src/content/reference/react/Component.md +++ b/src/content/reference/react/Component.md @@ -50,9 +50,9 @@ Only the `render` method is required, other methods are optional. ### `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). +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). -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 { @@ -565,7 +565,7 @@ class Greeting extends Component { React may call `render` at any moment, so you shouldn't assume that it runs at a particular time. Usually, the `render` method should return a piece of [JSX](/learn/writing-markup-with-jsx), but a few [other return types](#render-returns) (like strings) are supported. To calculate the returned JSX, the `render` method can read [`this.props`](#props), [`this.state`](#state), and [`this.context`](#context). -You should write the `render` method as a pure function, meaning that it should return the same result if props, state, and context are the same. It also shouldn't contain side effects (like setting up subscriptions) or interact with the browser APIs. Side effects should happen either in event handlers or methods like [`componentDidMount`.](#componentdidmount) +You should write the `render` method as a pure function, meaning that it should return the same result if props, state, and Context are the same. It also shouldn't contain side effects (like setting up subscriptions) or interact with the browser APIs. Side effects should happen either in event handlers or methods like [`componentDidMount`.](#componentdidmount) #### Parameters {/*render-parameters*/} @@ -714,7 +714,7 @@ React calls `shouldComponentUpdate` before rendering when new props or state are - `nextProps`: The next props that the component is about to render with. Compare `nextProps` to [`this.props`](#props) to determine what changed. - `nextState`: The next state that the component is about to render with. Compare `nextState` to [`this.state`](#props) to determine what changed. -- `nextContext`: The next context that the component is about to render with. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype). +- `nextContext`: The next Context that the component is about to render with. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype). #### Returns {/*shouldcomponentupdate-returns*/} @@ -789,7 +789,7 @@ If you define `UNSAFE_componentWillReceiveProps`, React will call it when the co #### Parameters {/*unsafe_componentwillreceiveprops-parameters*/} - `nextProps`: The next props that the component is about to receive from its parent component. Compare `nextProps` to [`this.props`](#props) to determine what changed. -- `nextContext`: The next context that the component is about to receive from the closest provider. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype). +- `nextContext`: The next Context that the component is about to receive from the closest provider. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype). #### Returns {/*unsafe_componentwillreceiveprops-returns*/} @@ -856,7 +856,7 @@ There is no direct equivalent to `UNSAFE_componentWillUpdate` in function compon ### `static contextType` {/*static-contexttype*/} -If you want to read [`this.context`](#context-instance-field) from your class component, you must specify which context it needs to read. The context you specify as the `static contextType` must be a value previously created by [`createContext`.](/reference/react/createContext) +If you want to read [`this.context`](#context-instance-field) from your class component, you must specify which Context it needs to read. The Context you specify as the `static contextType` must be a value previously created by [`createContext`.](/reference/react/createContext) ```js {2} class Button extends Component { @@ -1773,9 +1773,9 @@ If your component does not synchronize with any external systems, [you might not --- -### Migrating a component with context from a class to a function {/*migrating-a-component-with-context-from-a-class-to-a-function*/} +### Migrating a component with Context from a class to a function {/*migrating-a-component-with-context-from-a-class-to-a-function*/} -In this example, the `Panel` and `Button` class components read [context](/learn/passing-data-deeply-with-context) from [`this.context`:](#context) +In this example, the `Panel` and `Button` class components read [Context](/learn/passing-data-deeply-with-context) from [`this.context`:](#context) 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/apis.md b/src/content/reference/react/apis.md index 777b8fc7b93..35065942dfd 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/hooks) and [Components](/reference/react --- -* [`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) * [`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) * [`startTransition`](/reference/react/startTransition) lets you mark a state update as non-urgent. Similar to [`useTransition`.](/reference/react/useTransition) @@ -20,11 +20,11 @@ In addition to [Hooks](/reference/react/hooks) and [Components](/reference/react ## Resource APIs {/*resource-apis*/} -*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 API: -* [`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 }) { const message = use(messagePromise); diff --git a/src/content/reference/react/createContext.md b/src/content/reference/react/createContext.md index e4e9bcf6219..abf968fb16e 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,23 +32,23 @@ 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) 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) 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` lets you provide the context value to components. -* `SomeContext.Consumer` is an alternative and rarely used way to read the context value. -* `SomeContext.Provider` is a legacy way to provide the context value before React 19. +* `SomeContext` lets you provide the Context value to components. +* `SomeContext.Consumer` is an alternative and rarely used way to read the Context value. +* `SomeContext.Provider` is a legacy way to provide the Context value before React 19. --- ### `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() { @@ -72,13 +72,13 @@ In older versions of React, use ``. #### 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() { @@ -93,7 +93,7 @@ function Button() { } ``` -Although this older way still works, **newly written code should read context with [`useContext()`](/reference/react/useContext) instead:** +Although this older way still works, **newly written code should read Context with [`useContext()`](/reference/react/useContext) instead:** ```js function Button() { @@ -105,17 +105,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'; @@ -124,7 +124,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() { @@ -138,7 +138,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:** @@ -159,15 +159,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 @@ -177,7 +177,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 @@ -211,10 +211,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'); @@ -222,4 +222,4 @@ 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/memo.md b/src/content/reference/react/memo.md index b91171e8fd2..2ed0b0a49a2 100644 --- a/src/content/reference/react/memo.md +++ b/src/content/reference/react/memo.md @@ -66,7 +66,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): @@ -213,9 +213,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. @@ -269,7 +269,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 1780f82e7b5..9b0d49fce61 100644 --- a/src/content/reference/react/use.md +++ b/src/content/reference/react/use.md @@ -4,7 +4,7 @@ title: use -`use` is a React API that lets you read the 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). +`use` is a React API that lets you read the 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). ```js const value = use(resource); @@ -20,7 +20,7 @@ const value = use(resource); ### `use(context)` {/*use-context*/} -Call `use` with a [context](/learn/passing-data-deeply-with-context) to read its value. Unlike [`useContext`](/reference/react/useContext), `use` can be called within loops and conditional statements like `if`. +Call `use` with a [Context](/learn/passing-data-deeply-with-context) to read its value. Unlike [`useContext`](/reference/react/useContext), `use` can be called within loops and conditional statements like `if`. ```js import { use } from 'react'; @@ -34,16 +34,16 @@ function Button() { #### Parameters {/*context-parameters*/} -* `context`: A [context](/learn/passing-data-deeply-with-context) created with [`createContext`](/reference/react/createContext). +* `context`: A [Context](/learn/passing-data-deeply-with-context) created with [`createContext`](/reference/react/createContext). #### Returns {/*context-returns*/} -The context value for the passed context, determined by the closest context provider above the calling component. If there is no provider, the returned value is the `defaultValue` passed to [`createContext`](/reference/react/createContext). +The Context value for the passed Context, determined by the closest Context provider above the calling component. If there is no provider, the returned value is the `defaultValue` passed to [`createContext`](/reference/react/createContext). #### Caveats {/*context-caveats*/} * `use` must be called inside a Component or a Hook. -* Reading context with `use` is not supported in [Server Components](/reference/rsc/server-components). +* Reading Context with `use` is not supported in [Server Components](/reference/rsc/server-components). --- @@ -82,9 +82,9 @@ The resolved value of the Promise. ## Usage (Context) {/*usage-context*/} -### 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`. +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`. ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { use } from 'react'; @@ -94,9 +94,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() { @@ -130,7 +130,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)`. @@ -221,9 +221,9 @@ function Button({ show, children }) { -### Reading a Promise from context {/*reading-a-promise-from-context*/} +### Reading a Promise from Context {/*reading-a-promise-from-context*/} -To share asynchronous data without prop drilling, set a Promise as a context value, then read it with `use(context)` and resolve it with `use(promise)`: +To share asynchronous data without prop drilling, set a Promise as a Context value, then read it with `use(context)` and resolve it with `use(promise)`: ```js import { use } from 'react'; @@ -236,13 +236,13 @@ function Profile() { } ``` -Reading the value requires two `use` calls because the context value itself isn't awaited. See [Before you use context](/learn/passing-data-deeply-with-context#before-you-use-context) for alternatives to consider before reaching for context. +Reading the value requires two `use` calls because the Context value itself isn't awaited. See [Before you use Context](/learn/passing-data-deeply-with-context#before-you-use-context) for alternatives to consider before reaching for Context. Wrap the components that read the Promise in a [Suspense](/reference/react/Suspense) boundary so only that subtree suspends while the Promise is pending. See [Usage (Promises)](#usage-promises) below for more on reading Promises with `use`. -When this pattern is used with [Server Components](/reference/rsc/server-components), refetching the Promise requires refetching the Server Component that sets the Promise in context. Avoid setting the Promise in context high in the tree, since that would refetch large parts of the app unnecessarily. +When this pattern is used with [Server Components](/reference/rsc/server-components), refetching the Promise requires refetching the Server Component that sets the Promise in Context. Avoid setting the Promise in Context high in the tree, since that would refetch large parts of the app unnecessarily. diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md index 022277df40f..5f0f1831c1b 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` 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` 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. @@ -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 6f7728f0a2a..92930c09d3f 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 9bb755a4be9..69f9ba8e069 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 973561c2251..6c560fd05c7 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): 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.