diff --git a/src/content/learn/adding-interactivity.md b/src/content/learn/adding-interactivity.md index 0e84780fa60..897474bc758 100644 --- a/src/content/learn/adding-interactivity.md +++ b/src/content/learn/adding-interactivity.md @@ -257,7 +257,7 @@ Read **[Render and Commit](/learn/render-and-commit)** to learn the lifecycle of ## State as a snapshot {/*state-as-a-snapshot*/} -Unlike regular JavaScript variables, React state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first! +Unlike regular JavaScript variables, React State behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first! ```js console.log(count); // 0 @@ -408,7 +408,7 @@ Read **[Queueing a Series of State Updates](/learn/queueing-a-series-of-state-up ## Updating objects in state {/*updating-objects-in-state*/} -State can hold any kind of JavaScript value, including objects. But you shouldn't change objects and arrays that you hold in the React state directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy. +State can hold any kind of JavaScript value, including objects. But you shouldn't change objects and arrays that you hold in the React State directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy. Usually, you will use the `...` spread syntax to copy objects and arrays that you want to change. For example, updating a nested object could look like this: diff --git a/src/content/learn/escape-hatches.md b/src/content/learn/escape-hatches.md index cbaef8bb36f..e932818dc7a 100644 --- a/src/content/learn/escape-hatches.md +++ b/src/content/learn/escape-hatches.md @@ -99,7 +99,7 @@ Read **[Manipulating the DOM with Refs](/learn/manipulating-the-dom-with-refs)** ## Synchronizing with Effects {/*synchronizing-with-effects*/} -Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. Unlike event handlers, which let you handle particular events, *Effects* let you run some code after rendering. Use them to synchronize your component with a system outside of React. +Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React State, set up a server connection, or send an analytics log when a component appears on the screen. Unlike event handlers, which let you handle particular events, *Effects* let you run some code after rendering. Use them to synchronize your component with a system outside of React. Press Play/Pause a few times and see how the video player stays synchronized to the `isPlaying` prop value: diff --git a/src/content/learn/importing-and-exporting-components.md b/src/content/learn/importing-and-exporting-components.md index 16cd509f079..0b78a3c62f7 100644 --- a/src/content/learn/importing-and-exporting-components.md +++ b/src/content/learn/importing-and-exporting-components.md @@ -59,7 +59,7 @@ These currently live in a **root component file,** named `App.js` in this exampl What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps: 1. **Make** a new JS file to put the components in. -2. **Export** your function component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports). +2. **Export** your Function Component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports). 3. **Import** it in the file where you’ll use the component (using the corresponding technique for importing [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module) exports). Here both `Profile` and `Gallery` have been moved out of `App.js` into a new file called `Gallery.js`. Now you can change `App.js` to import `Gallery` from `Gallery.js`: diff --git a/src/content/learn/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md index 5bf8e0a79b8..42b3115575f 100644 --- a/src/content/learn/keeping-components-pure.md +++ b/src/content/learn/keeping-components-pure.md @@ -87,7 +87,7 @@ You could think of your components as recipes: if you follow them and don't intr ## Side Effects: (un)intended consequences {/*side-effects-unintended-consequences*/} -React's rendering process must always be pure. Components should only *return* their JSX, and not *change* any objects or variables that existed before rendering—that would make them impure! +React's rendering process must always be pure, and components should only *return* their JSX, and not *change* any objects or variables that existed before rendering—that would make them impure! Here is a component that breaks this rule: @@ -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 608db09a00e..d205d54a81e 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 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..a003cd4b5a1 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: @@ -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. * 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/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md index 685f63ef4ae..b16878dc351 100644 --- a/src/content/learn/preserving-and-resetting-state.md +++ b/src/content/learn/preserving-and-resetting-state.md @@ -1229,7 +1229,7 @@ In a real chat app, you'd probably want to recover the input state when the user - You could render _all_ chats instead of just the current one, but hide all the others with CSS. The chats would not get removed from the tree, so their local state would be preserved. This solution works great for simple UIs. But it can get very slow if the hidden trees are large and contain a lot of DOM nodes. - You could [lift the state up](/learn/sharing-state-between-components) and hold the pending message for each recipient in the parent component. This way, when the child components get removed, it doesn't matter, because it's the parent that keeps the important information. This is the most common solution. -- You might also use a different source in addition to React state. For example, you probably want a message draft to persist even if the user accidentally closes the page. To implement this, you could have the `Chat` component initialize its state by reading from the [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), and save the drafts there too. +- You might also use a different source in addition to React State. For example, you probably want a message draft to persist even if the user accidentally closes the page. To implement this, you could have the `Chat` component initialize its state by reading from the [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), and save the drafts there too. No matter which strategy you pick, a chat _with Alice_ is conceptually distinct from a chat _with Bob_, so it makes sense to give a `key` to the `` tree based on the current recipient. diff --git a/src/content/learn/react-compiler/introduction.md b/src/content/learn/react-compiler/introduction.md index ff5d6eae483..089d2701785 100644 --- a/src/content/learn/react-compiler/introduction.md +++ b/src/content/learn/react-compiler/introduction.md @@ -99,7 +99,7 @@ React Compiler's automatic memoization is primarily focused on **improving updat #### Optimizing Re-renders {/*optimizing-re-renders*/} -React lets you express your UI as a function of their current state (more concretely: their props, state, and context). In its current implementation, when a component's state changes, React will re-render that component _and all of its children_ — unless you have applied some form of manual memoization with `useMemo()`, `useCallback()`, or `React.memo()`. For example, in the following example, `` will re-render whenever ``'s state changes: +React lets you express your UI as a function of their current state (more concretely: their props, state, and Context). In its current implementation, when a component's state changes, React will re-render that component _and all of its children_ — unless you have applied some form of manual memoization with `useMemo()`, `useCallback()`, or `React.memo()`. For example, in the following example, `` will re-render whenever ``'s state changes: ```javascript function FriendList({ friends }) { diff --git a/src/content/learn/referencing-values-with-refs.md b/src/content/learn/referencing-values-with-refs.md index 657d3ddcb00..c8db3499394 100644 --- a/src/content/learn/referencing-values-with-refs.md +++ b/src/content/learn/referencing-values-with-refs.md @@ -271,7 +271,7 @@ Following these principles will make your components more predictable: - **Treat refs as an escape hatch.** Refs are useful when you work with external systems or browser APIs. If much of your application logic and data flow relies on refs, you might want to rethink your approach. - **Don't read or write `ref.current` during rendering.** If some information is needed during rendering, use [state](/learn/state-a-components-memory) instead. Since React doesn't know when `ref.current` changes, even reading it while rendering makes your component's behavior difficult to predict. (The only exception to this is code like `if (!ref.current) ref.current = new Thing()` which only sets the ref once during the first render.) -Limitations of React state don't apply to refs. For example, state acts like a [snapshot for every render](/learn/state-as-a-snapshot) and [doesn't update synchronously.](/learn/queueing-a-series-of-state-updates) But when you mutate the current value of a ref, it changes immediately: +Limitations of React State don't apply to refs. For example, state acts like a [snapshot for every render](/learn/state-as-a-snapshot) and [doesn't update synchronously.](/learn/queueing-a-series-of-state-updates) But when you mutate the current value of a ref, it changes immediately: ```js ref.current = 5; diff --git a/src/content/learn/render-and-commit.md b/src/content/learn/render-and-commit.md index 055111c3225..d098fe2fe0b 100644 --- a/src/content/learn/render-and-commit.md +++ b/src/content/learn/render-and-commit.md @@ -80,7 +80,7 @@ Once the component has been initially rendered, you can trigger further renders After you trigger a render, React calls your components to figure out what to display on screen. **"Rendering" is React calling your components.** * **On initial render,** React will call the root component. -* **For subsequent renders,** React will call the function component whose state update triggered the render. +* **For subsequent renders,** React will call the Function Component whose state update triggered the render. This process is recursive: if the updated component returns some other component, React will render _that_ component next, and if that component also returns something, it will render _that_ component next, and so on. The process will continue until there are no more nested components and React knows exactly what should be displayed on screen. diff --git a/src/content/learn/reusing-logic-with-custom-hooks.md b/src/content/learn/reusing-logic-with-custom-hooks.md index 47a4cf52a18..805620bb98f 100644 --- a/src/content/learn/reusing-logic-with-custom-hooks.md +++ b/src/content/learn/reusing-logic-with-custom-hooks.md @@ -224,7 +224,7 @@ You must follow these naming conventions: 1. **React component names must start with a capital letter,** like `StatusBar` and `SaveButton`. React components also need to return something that React knows how to display, like a piece of JSX. 2. **Hook names must start with `use` followed by a capital letter,** like [`useState`](/reference/react/useState) (built-in) or `useOnlineStatus` (custom, like earlier on the page). Hooks may return arbitrary values. -This convention guarantees that you can always look at a component and know where its state, Effects, and other React features might "hide". For example, if you see a `getColor()` function call inside your component, you can be sure that it can't possibly contain React state inside because its name doesn't start with `use`. However, a function call like `useOnlineStatus()` will most likely contain calls to other Hooks inside! +This convention guarantees that you can always look at a component and know where its state, Effects, and other React features might "hide". For example, if you see a `getColor()` function call inside your component, you can be sure that it can't possibly contain React State inside because its name doesn't start with `use`. However, a function call like `useOnlineStatus()` will most likely contain calls to other Hooks inside! 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..1b2bcb9743e 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:** @@ -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/sharing-state-between-components.md b/src/content/learn/sharing-state-between-components.md index 2fbef891801..a927d5c0a8f 100644 --- a/src/content/learn/sharing-state-between-components.md +++ b/src/content/learn/sharing-state-between-components.md @@ -302,7 +302,7 @@ When writing a component, consider which information in it should be controlled ## A single source of truth for each state {/*a-single-source-of-truth-for-each-state*/} -In a React application, many components will have their own state. Some state may "live" close to the leaf components (components at the bottom of the tree) like inputs. Other state may "live" closer to the top of the app. For example, even client-side routing libraries are usually implemented by storing the current route in the React state, and passing it down by props! +In a React application, many components will have their own state. Some state may "live" close to the leaf components (components at the bottom of the tree) like inputs. Other state may "live" closer to the top of the app. For example, even client-side routing libraries are usually implemented by storing the current route in the React State, and passing it down by props! **For each unique piece of state, you will choose the component that "owns" it.** This principle is also known as having a ["single source of truth".](https://en.wikipedia.org/wiki/Single_source_of_truth) It doesn't mean that all state lives in one place--but that for _each_ piece of state, there is a _specific_ component that holds that piece of information. Instead of duplicating shared state between components, *lift it up* to their common shared parent, and *pass it down* to the children that need it. diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md index 1eec633882f..bb82710c524 100644 --- a/src/content/learn/synchronizing-with-effects.md +++ b/src/content/learn/synchronizing-with-effects.md @@ -4,7 +4,7 @@ title: 'Synchronizing with Effects' -Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. *Effects* let you run some code after rendering so that you can synchronize your component with some system outside of React. +Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React State, set up a server connection, or send an analytics log when a component appears on the screen. *Effects* let you run some code after rendering so that you can synchronize your component with some system outside of React. @@ -205,7 +205,7 @@ video { width: 250px; } -In this example, the "external system" you synchronized to React state was the browser media API. You can use a similar approach to wrap legacy non-React code (like jQuery plugins) into declarative React components. +In this example, the "external system" you synchronized to React State was the browser media API. You can use a similar approach to wrap legacy non-React code (like jQuery plugins) into declarative React components. Note that controlling a video player is much more complex in practice. Calling `play()` may fail, the user might play or pause using the built-in browser controls, and so on. This example is very simplified and incomplete. diff --git a/src/content/learn/typescript.md b/src/content/learn/typescript.md index 2e6f7edc53e..91aa76dbde4 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/learn/updating-arrays-in-state.md b/src/content/learn/updating-arrays-in-state.md index 61e4f4e2d98..c1eb9f8b38b 100644 --- a/src/content/learn/updating-arrays-in-state.md +++ b/src/content/learn/updating-arrays-in-state.md @@ -10,7 +10,7 @@ Arrays are mutable in JavaScript, but you should treat them as immutable when yo -- How to add, remove, or change items in an array in React state +- How to add, remove, or change items in an array in React State - How to update an object inside of an array - How to make array copying less repetitive with Immer @@ -18,11 +18,11 @@ Arrays are mutable in JavaScript, but you should treat them as immutable when yo ## Updating arrays without mutation {/*updating-arrays-without-mutation*/} -In JavaScript, arrays are just another kind of object. [Like with objects](/learn/updating-objects-in-state), **you should treat arrays in React state as read-only.** This means that you shouldn't reassign items inside an array like `arr[0] = 'bird'`, and you also shouldn't use methods that mutate the array, such as `push()` and `pop()`. +In JavaScript, arrays are just another kind of object. [Like with objects](/learn/updating-objects-in-state), **you should treat arrays in React State as read-only.** This means that you shouldn't reassign items inside an array like `arr[0] = 'bird'`, and you also shouldn't use methods that mutate the array, such as `push()` and `pop()`. Instead, every time you want to update an array, you'll want to pass a *new* array to your state setting function. To do that, you can create a new array from the original array in your state by calling its non-mutating methods like `filter()` and `map()`. Then you can set your state to the resulting new array. -Here is a reference table of common array operations. When dealing with arrays inside React state, you will need to avoid the methods in the left column, and instead prefer the methods in the right column: +Here is a reference table of common array operations. When dealing with arrays inside React State, you will need to avoid the methods in the left column, and instead prefer the methods in the right column: | | avoid (mutates the array) | prefer (returns a new array) | | --------- | ----------------------------------- | ------------------------------------------------------------------- | diff --git a/src/content/learn/updating-objects-in-state.md b/src/content/learn/updating-objects-in-state.md index 5e04e7ae5cb..de5010843ab 100644 --- a/src/content/learn/updating-objects-in-state.md +++ b/src/content/learn/updating-objects-in-state.md @@ -4,13 +4,13 @@ title: Updating Objects in State -State can hold any kind of JavaScript value, including objects. But you shouldn't change objects that you hold in the React state directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy. +State can hold any kind of JavaScript value, including objects. But you shouldn't change objects that you hold in the React State directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy. -- How to correctly update an object in React state +- How to correctly update an object in React State - How to update a nested object without mutating it - What immutability is, and how not to break it - How to make object copying less repetitive with Immer @@ -45,7 +45,7 @@ Technically, it is possible to change the contents of _the object itself_. **Thi position.x = 5; ``` -However, although objects in React state are technically mutable, you should treat them **as if** they were immutable--like numbers, booleans, and strings. Instead of mutating them, you should always replace them. +However, although objects in React State are technically mutable, you should treat them **as if** they were immutable--like numbers, booleans, and strings. Instead of mutating them, you should always replace them. ## Treat state as read-only {/*treat-state-as-read-only*/} diff --git a/src/content/learn/you-might-not-need-an-effect.md b/src/content/learn/you-might-not-need-an-effect.md index 81a0842eb60..17c37470faa 100644 --- a/src/content/learn/you-might-not-need-an-effect.md +++ b/src/content/learn/you-might-not-need-an-effect.md @@ -26,7 +26,7 @@ There are two common cases in which you don't need Effects: * **You don't need Effects to transform data for rendering.** For example, let's say you want to filter a list before displaying it. You might feel tempted to write an Effect that updates a state variable when the list changes. However, this is inefficient. When you update the state, React will first call your component functions to calculate what should be on the screen. Then React will ["commit"](/learn/render-and-commit) these changes to the DOM, updating the screen. Then React will run your Effects. If your Effect *also* immediately updates the state, this restarts the whole process from scratch! To avoid the unnecessary render passes, transform all the data at the top level of your components. That code will automatically re-run whenever your props or state change. * **You don't need Effects to handle user events.** For example, let's say you want to send an `/api/buy` POST request and show a notification when the user buys a product. In the Buy button click event handler, you know exactly what happened. By the time an Effect runs, you don't know *what* the user did (for example, which button was clicked). This is why you'll usually handle user events in the corresponding event handlers. -You *do* need Effects to [synchronize](/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events) with external systems. For example, you can write an Effect that keeps a jQuery widget synchronized with the React state. You can also fetch data with Effects: for example, you can synchronize the search results with the current search query. Keep in mind that modern [frameworks](/learn/creating-a-react-app#full-stack-frameworks) provide more efficient built-in data fetching mechanisms than writing Effects directly in your components. +You *do* need Effects to [synchronize](/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events) with external systems. For example, you can write an Effect that keeps a jQuery widget synchronized with the React State. You can also fetch data with Effects: for example, you can synchronize the search results with the current search query. Keep in mind that modern [frameworks](/learn/creating-a-react-app#full-stack-frameworks) provide more efficient built-in data fetching mechanisms than writing Effects directly in your components. To help you gain the right intuition, let's look at some common concrete examples! @@ -637,7 +637,7 @@ This is simpler and keeps the data flow predictable: the data flows down from th ### Subscribing to an external store {/*subscribing-to-an-external-store*/} -Sometimes, your components may need to subscribe to some data outside of the React state. This data could be from a third-party library or a built-in browser API. Since this data can change without React's knowledge, you need to manually subscribe your components to it. This is often done with an Effect, for example: +Sometimes, your components may need to subscribe to some data outside of the React State. This data could be from a third-party library or a built-in browser API. Since this data can change without React's knowledge, you need to manually subscribe your components to it. This is often done with an Effect, for example: ```js {2-17} function useOnlineStatus() { @@ -695,7 +695,7 @@ function ChatIndicator() { } ``` -This approach is less error-prone than manually syncing mutable data to React state with an Effect. Typically, you'll write a custom Hook like `useOnlineStatus()` above so that you don't need to repeat this code in the individual components. [Read more about subscribing to external stores from React components.](/reference/react/useSyncExternalStore) +This approach is less error-prone than manually syncing mutable data to React State with an Effect. Typically, you'll write a custom Hook like `useOnlineStatus()` above so that you don't need to repeat this code in the individual components. [Read more about subscribing to external stores from React components.](/reference/react/useSyncExternalStore) ### Fetching data {/*fetching-data*/} 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/eslint-plugin-react-hooks/lints/use-memo.md b/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md index a5a77e5f6e8..de10cad33b4 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/use-memo.md @@ -79,7 +79,7 @@ function Component({user}) { } ``` -If the side effect sychronizes React state with some external state (or vice versa), use `useEffect`: +If the side effect sychronizes React State with some external state (or vice versa), use `useEffect`: ```js // ✅ Good: Synchronization in useEffect 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-dom/flushSync.md b/src/content/reference/react-dom/flushSync.md index 6fe53337d44..d1f4cb7d3d3 100644 --- a/src/content/reference/react-dom/flushSync.md +++ b/src/content/reference/react-dom/flushSync.md @@ -79,7 +79,7 @@ However, it can be helpful for integrating with third-party code like browser AP Some browser APIs expect results inside of callbacks to be written to the DOM synchronously, by the end of the callback, so the browser can do something with the rendered DOM. In most cases, React handles this for you automatically. But in some cases it may be necessary to force a synchronous update. -For example, the browser `onbeforeprint` API allows you to change the page immediately before the print dialog opens. This is useful for applying custom print styles that allow the document to display better for printing. In the example below, you use `flushSync` inside of the `onbeforeprint` callback to immediately "flush" the React state to the DOM. Then, by the time the print dialog opens, `isPrinting` displays "yes": +For example, the browser `onbeforeprint` API allows you to change the page immediately before the print dialog opens. This is useful for applying custom print styles that allow the document to display better for printing. In the example below, you use `flushSync` inside of the `onbeforeprint` callback to immediately "flush" the React State to the DOM. Then, by the time the print dialog opens, `isPrinting` displays "yes": diff --git a/src/content/reference/react-dom/preinit.md b/src/content/reference/react-dom/preinit.md index d9f3808c465..5b34347148f 100644 --- a/src/content/reference/react-dom/preinit.md +++ b/src/content/reference/react-dom/preinit.md @@ -1,4 +1,4 @@ ---- +undefined- title: preinit --- diff --git a/src/content/reference/react/Component.md b/src/content/reference/react/Component.md index 3b882f09762..3510469779c 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). +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 { @@ -73,7 +73,7 @@ class Button extends Component { -Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components. +Reading `this.context` in Class Components is equivalent to [`useContext`](/reference/react/useContext) in Function Components. [See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function) @@ -83,7 +83,7 @@ Reading `this.context` in class components is equivalent to [`useContext`](/refe ### `props` {/*props*/} -The props passed to a class component are available as `this.props`. +The props passed to a Class Component are available as `this.props`. ```js {3} class Greeting extends Component { @@ -97,7 +97,7 @@ class Greeting extends Component { -Reading `this.props` in class components is equivalent to [declaring props](/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component) in function components. +Reading `this.props` in Class Components is equivalent to [declaring props](/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component) in Function Components. [See how to migrate.](#migrating-a-simple-component-from-a-class-to-a-function) @@ -107,7 +107,7 @@ Reading `this.props` in class components is equivalent to [declaring props](/lea ### `state` {/*state*/} -The state of a class component is available as `this.state`. The `state` field must be an object. Do not mutate the state directly. If you wish to change the state, call `setState` with the new state. +The state of a Class Component is available as `this.state`. The `state` field must be an object. Do not mutate the state directly. If you wish to change the state, call `setState` with the new state. ```js {2-4,7-9,18} class Counter extends Component { @@ -136,7 +136,7 @@ class Counter extends Component { -Defining `state` in class components is equivalent to calling [`useState`](/reference/react/useState) in function components. +Defining `state` in Class Components is equivalent to calling [`useState`](/reference/react/useState) in Function Components. [See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function) @@ -146,7 +146,7 @@ Defining `state` in class components is equivalent to calling [`useState`](/refe ### `constructor(props)` {/*constructor*/} -The [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) runs before your class component *mounts* (gets added to the screen). Typically, a constructor is only used for two purposes in React. It lets you declare state and [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) your class methods to the class instance: +The [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) runs before your Class Component *mounts* (gets added to the screen). Typically, a constructor is only used for two purposes in React. It lets you declare state and [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) your class methods to the class instance: ```js {2-6} class Counter extends Component { @@ -196,7 +196,7 @@ A constructor should not contain any side effects or subscriptions. -There is no exact equivalent for `constructor` in function components. To declare state in a function component, call [`useState`.](/reference/react/useState) To avoid recalculating the initial state, [pass a function to `useState`.](/reference/react/useState#avoiding-recreating-the-initial-state) +There is no exact equivalent for `constructor` in Function Components. To declare state in a Function Component, call [`useState`.](/reference/react/useState) To avoid recalculating the initial state, [pass a function to `useState`.](/reference/react/useState#avoiding-recreating-the-initial-state) @@ -228,7 +228,7 @@ Typically, it is used together with [`static getDerivedStateFromError`](#static- -There is no direct equivalent for `componentDidCatch` in function components yet. If you'd like to avoid creating class components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, you can use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that for you. +There is no direct equivalent for `componentDidCatch` in Function Components yet. If you'd like to avoid creating Class Components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, you can use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that for you. @@ -286,7 +286,7 @@ class ChatRoom extends Component { -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in Class Components is equivalent to calling [`useEffect`](/reference/react/useEffect) in Function Components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. [See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) @@ -353,7 +353,7 @@ class ChatRoom extends Component { -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in Class Components is equivalent to calling [`useEffect`](/reference/react/useEffect) in Function Components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. [See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) @@ -446,7 +446,7 @@ class ChatRoom extends Component { -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in Class Components is equivalent to calling [`useEffect`](/reference/react/useEffect) in Function Components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. [See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) @@ -476,7 +476,7 @@ Try to avoid all uses of `forceUpdate` and only read from `this.props` and `this -Reading an external data source and forcing class components to re-render in response to its changes with `forceUpdate` has been superseded by [`useSyncExternalStore`](/reference/react/useSyncExternalStore) in function components. +Reading an external data source and forcing Class Components to re-render in response to its changes with `forceUpdate` has been superseded by [`useSyncExternalStore`](/reference/react/useSyncExternalStore) in Function Components. @@ -541,7 +541,7 @@ You should return a snapshot value of any type that you'd like, or `null`. The v -At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for function components. This use case is very uncommon, but if you have the need for it, for now you'll have to write a class component. +At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for Function Components. This use case is very uncommon, but if you have the need for it, for now you'll have to write a Class Component. @@ -549,7 +549,7 @@ At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for function ### `render()` {/*render*/} -The `render` method is the only required method in a class component. +The `render` method is the only required method in a Class Component. The `render` method should specify what you want to appear on the screen, for example: @@ -669,7 +669,7 @@ You don't have to do this, but it's handy if you want to update state multiple t -Calling `setState` in class components is similar to calling a [`set` function](/reference/react/useState#setstate) in function components. +Calling `setState` in Class Components is similar to calling a [`set` function](/reference/react/useState#setstate) in Function Components. [See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function) @@ -736,7 +736,7 @@ Return `false` to tell React that re-rendering can be skipped. -Optimizing class components with `shouldComponentUpdate` is similar to optimizing function components with [`memo`.](/reference/react/memo) Function components also offer more granular optimization with [`useMemo`.](/reference/react/useMemo) +Optimizing Class Components with `shouldComponentUpdate` is similar to optimizing Function Components with [`memo`.](/reference/react/memo) Function components also offer more granular optimization with [`useMemo`.](/reference/react/useMemo) @@ -769,7 +769,7 @@ If you define `UNSAFE_componentWillMount`, React will call it immediately after -Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a class component to initialize state is equivalent to passing that state as the initial state to [`useState`](/reference/react/useState) in a function component. +Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a Class Component to initialize state is equivalent to passing that state as the initial state to [`useState`](/reference/react/useState) in a Function Component. @@ -807,7 +807,7 @@ If you define `UNSAFE_componentWillReceiveProps`, React will call it when the co -Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a class component to "adjust" state is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component. +Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a Class Component to "adjust" state is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a Function Component. @@ -848,7 +848,7 @@ If you define `UNSAFE_componentWillUpdate`, React will call it before rendering -There is no direct equivalent to `UNSAFE_componentWillUpdate` in function components. +There is no direct equivalent to `UNSAFE_componentWillUpdate` in Function Components. @@ -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 { @@ -876,7 +876,7 @@ class Button extends Component { -Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components. +Reading `this.context` in Class Components is equivalent to [`useContext`](/reference/react/useContext) in Function Components. [See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function) @@ -922,7 +922,7 @@ If the `color` prop is not provided or is `undefined`, it will be set by default -Defining `defaultProps` in class components is similar to using [default values](/learn/passing-props-to-a-component#specifying-a-default-value-for-a-prop) in function components. +Defining `defaultProps` in Class Components is similar to using [default values](/learn/passing-props-to-a-component#specifying-a-default-value-for-a-prop) in Function Components. @@ -950,7 +950,7 @@ Typically, it is used together with [`componentDidCatch`](#componentdidcatch) wh -There is no direct equivalent for `static getDerivedStateFromError` in function components yet. If you'd like to avoid creating class components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that. +There is no direct equivalent for `static getDerivedStateFromError` in Function Components yet. If you'd like to avoid creating Class Components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that. @@ -1015,7 +1015,7 @@ Deriving state leads to verbose code and makes your components difficult to thin -Implementing `static getDerivedStateFromProps` in a class component is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component. +Implementing `static getDerivedStateFromProps` in a Class Component is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a Function Component. @@ -1023,7 +1023,7 @@ Implementing `static getDerivedStateFromProps` in a class component is equivalen ## Usage {/*usage*/} -### Defining a class component {/*defining-a-class-component*/} +### Defining a Class Component {/*defining-a-class-component*/} To define a React component as a class, extend the built-in `Component` class and define a [`render` method:](#render) @@ -1039,7 +1039,7 @@ class Greeting extends Component { React will call your [`render`](#render) method whenever it needs to figure out what to display on the screen. Usually, you will return some [JSX](/learn/writing-markup-with-jsx) from it. Your `render` method should be a [pure function:](https://en.wikipedia.org/wiki/Pure_function) it should only calculate the JSX. -Similarly to [function components,](/learn/your-first-component#defining-a-component) a class component can [receive information by props](/learn/your-first-component#defining-a-component) from its parent component. However, the syntax for reading props is different. For example, if the parent component renders ``, then you can read the `name` prop from [`this.props`](#props), like `this.props.name`: +Similarly to [Function Components,](/learn/your-first-component#defining-a-component) a Class Component can [receive information by props](/learn/your-first-component#defining-a-component) from its parent component. However, the syntax for reading props is different. For example, if the parent component renders ``, then you can read the `name` prop from [`this.props`](#props), like `this.props.name`: @@ -1065,7 +1065,7 @@ export default function App() { -Note that Hooks (functions starting with `use`, like [`useState`](/reference/react/useState)) are not supported inside class components. +Note that Hooks (functions starting with `use`, like [`useState`](/reference/react/useState)) are not supported inside Class Components. @@ -1075,7 +1075,7 @@ We recommend defining components as functions instead of classes. [See how to mi --- -### Adding state to a class component {/*adding-state-to-a-class-component*/} +### Adding state to a Class Component {/*adding-state-to-a-class-component*/} To add [state](/learn/state-a-components-memory) to a class, assign an object to a property called [`state`](#state). To update state, call [`this.setState`](#setstate). @@ -1133,7 +1133,7 @@ We recommend defining components as functions instead of classes. [See how to mi --- -### Adding lifecycle methods to a class component {/*adding-lifecycle-methods-to-a-class-component*/} +### Adding lifecycle methods to a Class Component {/*adding-lifecycle-methods-to-a-class-component*/} There are a few special methods you can define on your class. @@ -1338,7 +1338,7 @@ You don't need to wrap every component into a separate Error Boundary. When you -There is currently no way to write an Error Boundary as a function component. However, you don't have to write the Error Boundary class yourself. For example, you can use [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) instead. +There is currently no way to write an Error Boundary as a Function Component. However, you don't have to write the Error Boundary class yourself. For example, you can use [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) instead. @@ -1350,7 +1350,7 @@ There is currently no way to write an Error Boundary as a function component. Ho Typically, you will [define components as functions](/learn/your-first-component#defining-a-component) instead. -For example, suppose you're converting this `Greeting` class component to a function: +For example, suppose you're converting this `Greeting` Class Component to a function: @@ -1418,7 +1418,7 @@ export default function App() { ### Migrating a component with state from a class to a function {/*migrating-a-component-with-state-from-a-class-to-a-function*/} -Suppose you're converting this `Counter` class component to a function: +Suppose you're converting this `Counter` Class Component to a function: @@ -1540,7 +1540,7 @@ button { display: block; margin-top: 10px; } ### Migrating a component with lifecycle methods from a class to a function {/*migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function*/} -Suppose you're converting this `ChatRoom` class component with lifecycle methods to a function: +Suppose you're converting this `ChatRoom` Class Component with lifecycle methods to a function: @@ -1775,7 +1775,7 @@ 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*/} -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) @@ -1869,7 +1869,7 @@ export default function MyApp() { -When you convert them to function components, replace `this.context` with [`useContext`](/reference/react/useContext) calls: +When you convert them to Function Components, replace `this.context` with [`useContext`](/reference/react/useContext) calls: diff --git a/src/content/reference/react/PureComponent.md b/src/content/reference/react/PureComponent.md index 3e2d074e10d..3cc8c59ca33 100644 --- a/src/content/reference/react/PureComponent.md +++ b/src/content/reference/react/PureComponent.md @@ -30,7 +30,7 @@ class Greeting extends PureComponent { ### `PureComponent` {/*purecomponent*/} -To skip re-rendering a class component for same props and state, extend `PureComponent` instead of [`Component`:](/reference/react/Component) +To skip re-rendering a Class Component for same props and state, extend `PureComponent` instead of [`Component`:](/reference/react/Component) ```js import { PureComponent } from 'react'; @@ -51,7 +51,7 @@ class Greeting extends PureComponent { ## Usage {/*usage*/} -### Skipping unnecessary re-renders for class components {/*skipping-unnecessary-re-renders-for-class-components*/} +### Skipping unnecessary re-renders for Class Components {/*skipping-unnecessary-re-renders-for-class-components*/} React normally re-renders a component whenever its parent re-renders. As an optimization, you can create a component that React will not re-render when its parent re-renders so long as its new props and state are the same as the old props and state. [Class components](/reference/react/Component) can opt into this behavior by extending `PureComponent`: @@ -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): @@ -117,9 +117,9 @@ We recommend defining components as functions instead of classes. [See how to mi ## Alternatives {/*alternatives*/} -### Migrating from a `PureComponent` class component to a function {/*migrating-from-a-purecomponent-class-component-to-a-function*/} +### Migrating from a `PureComponent` Class Component to a function {/*migrating-from-a-purecomponent-class-component-to-a-function*/} -We recommend using function components instead of [class components](/reference/react/Component) in new code. If you have some existing class components using `PureComponent`, here is how you can convert them. This is the original code: +We recommend using Function Components instead of [Class Components](/reference/react/Component) in new code. If you have some existing Class Components using `PureComponent`, here is how you can convert them. This is the original code: @@ -203,6 +203,6 @@ label { -Unlike `PureComponent`, [`memo`](/reference/react/memo) does not compare the new and the old state. In function components, calling the [`set` function](/reference/react/useState#setstate) with the same state [already prevents re-renders by default,](/reference/react/memo#updating-a-memoized-component-using-state) even without `memo`. +Unlike `PureComponent`, [`memo`](/reference/react/memo) does not compare the new and the old state. In Function Components, calling the [`set` function](/reference/react/useState#setstate) with the same state [already prevents re-renders by default,](/reference/react/memo#updating-a-memoized-component-using-state) even without `memo`. diff --git a/src/content/reference/react/StrictMode.md b/src/content/reference/react/StrictMode.md index 16e8d9e6065..86d1eae554c 100644 --- a/src/content/reference/react/StrictMode.md +++ b/src/content/reference/react/StrictMode.md @@ -132,13 +132,13 @@ When `StrictMode` is enabled for a part of the app, React will only enable behav ### 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: - Your component function body (only top-level logic, so this doesn't include code inside event handlers) - Functions that you pass to [`useState`](/reference/react/useState), [`set` functions](/reference/react/useState#setstate), [`useMemo`](/reference/react/useMemo), or [`useReducer`](/reference/react/useReducer) -- Some class component methods like [`constructor`](/reference/react/Component#constructor), [`render`](/reference/react/Component#render), [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) ([see the whole list](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)) +- Some Class Component methods like [`constructor`](/reference/react/Component#constructor), [`render`](/reference/react/Component#render), [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) ([see the whole list](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)) If a function is pure, running it twice does not change its behavior because a pure function produces the same result every time. However, if a function is impure (for example, it mutates the data it receives), running it twice tends to be noticeable (that's what makes it impure!) This helps you spot and fix the bug early. @@ -1248,4 +1248,4 @@ React warns if some component anywhere inside a `` tree uses one of * `UNSAFE_` class lifecycle methods like [`UNSAFE_componentWillMount`](/reference/react/Component#unsafe_componentwillmount). [See alternatives.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles) -These APIs are primarily used in older [class components](/reference/react/Component) so they rarely appear in modern apps. +These APIs are primarily used in older [Class Components](/reference/react/Component) so they rarely appear in modern apps. diff --git a/src/content/reference/react/apis.md b/src/content/reference/react/apis.md index 777b8fc7b93..9ca40502ac6 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) diff --git a/src/content/reference/react/cloneElement.md b/src/content/reference/react/cloneElement.md index 91d501b7203..993c9577496 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 e4e9bcf6219..281c807f09a 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: * `SomeContext` lets you provide the context value to components. -* `SomeContext.Consumer` is an alternative and rarely used way to read the context value. +* `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() { @@ -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/createRef.md b/src/content/reference/react/createRef.md index 2a3ba6aa3df..c8ba59fe8a3 100644 --- a/src/content/reference/react/createRef.md +++ b/src/content/reference/react/createRef.md @@ -4,7 +4,7 @@ title: createRef -`createRef` is mostly used for [class components.](/reference/react/Component) Function components typically rely on [`useRef`](/reference/react/useRef) instead. +`createRef` is mostly used for [Class Components.](/reference/react/Component) Function components typically rely on [`useRef`](/reference/react/useRef) instead. @@ -29,7 +29,7 @@ class MyInput extends Component { ### `createRef()` {/*createref*/} -Call `createRef` to declare a [ref](/learn/referencing-values-with-refs) inside a [class component.](/reference/react/Component) +Call `createRef` to declare a [ref](/learn/referencing-values-with-refs) inside a [Class Component.](/reference/react/Component) ```js import { createRef, Component } from 'react'; @@ -55,16 +55,16 @@ class MyComponent extends Component { #### Caveats {/*caveats*/} * `createRef` always returns a *different* object. It's equivalent to writing `{ current: null }` yourself. -* In a function component, you probably want [`useRef`](/reference/react/useRef) instead which always returns the same object. +* In a Function Component, you probably want [`useRef`](/reference/react/useRef) instead which always returns the same object. * `const ref = useRef()` is equivalent to `const [ref, _] = useState(() => createRef(null))`. --- ## Usage {/*usage*/} -### Declaring a ref in a class component {/*declaring-a-ref-in-a-class-component*/} +### Declaring a ref in a Class Component {/*declaring-a-ref-in-a-class-component*/} -To declare a ref inside a [class component,](/reference/react/Component) call `createRef` and assign its result to a class field: +To declare a ref inside a [Class Component,](/reference/react/Component) call `createRef` and assign its result to a class field: ```js {4} import { Component, createRef } from 'react'; @@ -107,7 +107,7 @@ export default class Form extends Component { -`createRef` is mostly used for [class components.](/reference/react/Component) Function components typically rely on [`useRef`](/reference/react/useRef) instead. +`createRef` is mostly used for [Class Components.](/reference/react/Component) Function components typically rely on [`useRef`](/reference/react/useRef) instead. @@ -117,7 +117,7 @@ export default class Form extends Component { ### Migrating from a class with `createRef` to a function with `useRef` {/*migrating-from-a-class-with-createref-to-a-function-with-useref*/} -We recommend using function components instead of [class components](/reference/react/Component) in new code. If you have some existing class components using `createRef`, here is how you can convert them. This is the original code: +We recommend using Function Components instead of [Class Components](/reference/react/Component) in new code. If you have some existing Class Components using `createRef`, here is how you can convert them. This is the original code: diff --git a/src/content/reference/react/hooks.md b/src/content/reference/react/hooks.md index ab48b644b7f..59c1bf216ed 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() { 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..c8279073f73 100644 --- a/src/content/reference/react/use.md +++ b/src/content/reference/react/use.md @@ -82,7 +82,7 @@ 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`. @@ -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)`. @@ -236,7 +236,7 @@ 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`. diff --git a/src/content/reference/react/useContext.md b/src/content/reference/react/useContext.md index 02069c363a2..6b9231f6a8e 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,7 +34,7 @@ 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*/} @@ -43,8 +43,8 @@ function MyComponent() { #### 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: 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..2734fd50dc1 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. @@ -136,7 +136,7 @@ export default function TodosApp() { // that you might need to integrate with React. // If your app is fully built with React, -// we recommend using React state instead. +// we recommend using React State instead. let nextId = 0; let todos = [{ id: nextId++, text: 'Todo #1' }]; @@ -169,7 +169,7 @@ function emitChange() { -When possible, we recommend using built-in React state with [`useState`](/reference/react/useState) and [`useReducer`](/reference/react/useReducer) instead. The `useSyncExternalStore` API is mostly useful if you need to integrate with existing non-React code. +When possible, we recommend using built-in React State with [`useState`](/reference/react/useState) and [`useReducer`](/reference/react/useReducer) instead. The `useSyncExternalStore` API is mostly useful if you need to integrate with existing non-React code. 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..7a019a6a905 100644 --- a/src/content/reference/rules/index.md +++ b/src/content/reference/rules/index.md @@ -1,4 +1,4 @@ ---- +undefined- title: Rules of React --- @@ -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. @@ -38,7 +38,7 @@ We strongly recommend using [Strict Mode](/reference/react/StrictMode) alongside [React is responsible for rendering components and hooks when necessary to optimize the user experience.](/reference/rules/react-calls-components-and-hooks) It is declarative: you tell React what to render in your component’s logic, and React will figure out how best to display it to your user. -* [Never call component functions directly](/reference/rules/react-calls-components-and-hooks#never-call-component-functions-directly) – Components should only be used in JSX. Don’t call them as regular functions. +* [Never call component functions directly](/reference/rules/react-calls-components-and-hooks#never-call-component-functions-directly) – components should only be used in JSX. Don’t call them as regular functions. * [Never pass around hooks as regular values](/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values) – Hooks should only be called inside of components. Never pass it around as a regular value. --- diff --git a/src/content/reference/rules/react-calls-components-and-hooks.md b/src/content/reference/rules/react-calls-components-and-hooks.md index 03354ad5a73..9930f5cec0f 100644 --- a/src/content/reference/rules/react-calls-components-and-hooks.md +++ b/src/content/reference/rules/react-calls-components-and-hooks.md @@ -11,7 +11,7 @@ React is responsible for rendering components and Hooks when necessary to optimi --- ## Never call component functions directly {/*never-call-component-functions-directly*/} -Components should only be used in JSX. Don't call them as regular functions. React should call it. +In JSX, components should only be used. Don't call them as regular functions. React should call it. React must decide when your component function is called [during rendering](/reference/rules/components-and-hooks-must-be-pure#how-does-react-run-your-code). In React, you do this using JSX. diff --git a/src/content/reference/rules/rules-of-hooks.md b/src/content/reference/rules/rules-of-hooks.md index ecaef7c60d9..45afa94be36 100644 --- a/src/content/reference/rules/rules-of-hooks.md +++ b/src/content/reference/rules/rules-of-hooks.md @@ -14,14 +14,14 @@ Hooks are defined using JavaScript functions, but they represent a special type Functions whose names start with `use` are called [*Hooks*](/reference/react) in React. -**Don’t call Hooks inside loops, conditions, nested functions, or `try`/`catch`/`finally` blocks.** Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component: +**Don’t call Hooks inside loops, conditions, nested functions, or `try`/`catch`/`finally` blocks.** Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a Function Component: -* ✅ Call them at the top level in the body of a [function component](/learn/your-first-component). +* ✅ Call them at the top level in the body of a [Function Component](/learn/your-first-component). * ✅ Call them at the top level in the body of a [custom Hook](/learn/reusing-logic-with-custom-hooks). ```js{2-3,8-9} function Counter() { - // ✅ Good: top-level in a function component + // ✅ Good: top-level in a Function Component const [count, setCount] = useState(0); // ... } @@ -38,7 +38,7 @@ It’s **not** supported to call Hooks (functions starting with `use`) in any ot * 🔴 Do not call Hooks inside conditions or loops. * 🔴 Do not call Hooks after a conditional `return` statement. * 🔴 Do not call Hooks in event handlers. -* 🔴 Do not call Hooks in class components. +* 🔴 Do not call Hooks in Class Components. * 🔴 Do not call Hooks inside functions passed to `useMemo`, `useReducer`, or `useEffect`. * 🔴 Do not call Hooks inside `try`/`catch`/`finally` blocks. @@ -89,7 +89,7 @@ function Bad() { class Bad extends React.Component { render() { - // 🔴 Bad: inside a class component (to fix, write a function component instead of a class!) + // 🔴 Bad: inside a Class Component (to fix, write a Function Component instead of a class!) useEffect(() => {}) // ... } @@ -109,7 +109,7 @@ You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/packa -[Custom Hooks](/learn/reusing-logic-with-custom-hooks) *may* call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a function component is rendering. +[Custom Hooks](/learn/reusing-logic-with-custom-hooks) *may* call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a Function Component is rendering. @@ -119,7 +119,7 @@ You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/packa Don’t call Hooks from regular JavaScript functions. Instead, you can: -✅ Call Hooks from React function components. +✅ Call Hooks from React Function Components. ✅ Call Hooks from [custom Hooks](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component). By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code. diff --git a/src/content/warnings/invalid-hook-call-warning.md b/src/content/warnings/invalid-hook-call-warning.md index 5bbc2bbaae2..f6154f963a5 100644 --- a/src/content/warnings/invalid-hook-call-warning.md +++ b/src/content/warnings/invalid-hook-call-warning.md @@ -6,7 +6,7 @@ You are probably here because you got the following error message: -Hooks can only be called inside the body of a function component. +Hooks can only be called inside the body of a Function Component. @@ -22,14 +22,14 @@ Let's look at each of these cases. Functions whose names start with `use` are called [*Hooks*](/reference/react) in React. -**Don’t call Hooks inside loops, conditions, or nested functions.** Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component: +**Don’t call Hooks inside loops, conditions, or nested functions.** Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a Function Component: -* ✅ Call them at the top level in the body of a [function component](/learn/your-first-component). +* ✅ Call them at the top level in the body of a [Function Component](/learn/your-first-component). * ✅ Call them at the top level in the body of a [custom Hook](/learn/reusing-logic-with-custom-hooks). ```js{2-3,8-9} function Counter() { - // ✅ Good: top-level in a function component + // ✅ Good: top-level in a Function Component const [count, setCount] = useState(0); // ... } @@ -46,7 +46,7 @@ It’s **not** supported to call Hooks (functions starting with `use`) in any ot * 🔴 Do not call Hooks inside conditions or loops. * 🔴 Do not call Hooks after a conditional `return` statement. * 🔴 Do not call Hooks in event handlers. -* 🔴 Do not call Hooks in class components. +* 🔴 Do not call Hooks in Class Components. * 🔴 Do not call Hooks inside functions passed to `useMemo`, `useReducer`, or `useEffect`. If you break these rules, you might see this error. @@ -96,7 +96,7 @@ function Bad() { class Bad extends React.Component { render() { - // 🔴 Bad: inside a class component (to fix, write a function component instead of a class!) + // 🔴 Bad: inside a Class Component (to fix, write a Function Component instead of a class!) useEffect(() => {}) // ... } @@ -107,7 +107,7 @@ You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/packa -[Custom Hooks](/learn/reusing-logic-with-custom-hooks) *may* call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a function component is rendering. +[Custom Hooks](/learn/reusing-logic-with-custom-hooks) *may* call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a Function Component is rendering.