diff --git a/src/content/learn/adding-interactivity.md b/src/content/learn/adding-interactivity.md
index 0d4a3b23fce..da21dc6c629 100644
--- a/src/content/learn/adding-interactivity.md
+++ b/src/content/learn/adding-interactivity.md
@@ -4,19 +4,19 @@ title: Adding Interactivity
-Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called *state.* You can add state to any component, and update it as needed. In this chapter, you'll learn how to write components that handle interactions, update their state, and display different output over time.
+Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called *State.* You can add State to any component, and update it as needed. In this chapter, you'll learn how to write components that handle interactions, update their State, and display different output over time.
* [How to handle user-initiated events](/learn/responding-to-events)
-* [How to make components "remember" information with state](/learn/state-a-components-memory)
+* [How to make components "remember" information with State](/learn/state-a-components-memory)
* [How React updates the UI in two phases](/learn/render-and-commit)
-* [Why state doesn't update right after you change it](/learn/state-as-a-snapshot)
-* [How to queue multiple state updates](/learn/queueing-a-series-of-state-updates)
-* [How to update an object in state](/learn/updating-objects-in-state)
-* [How to update an array in state](/learn/updating-arrays-in-state)
+* [Why State doesn't update right after you change it](/learn/state-as-a-snapshot)
+* [How to queue multiple State updates](/learn/queueing-a-series-of-state-updates)
+* [How to update an object in State](/learn/updating-objects-in-state)
+* [How to update an array in State](/learn/updating-arrays-in-state)
@@ -74,16 +74,16 @@ Read **[Responding to Events](/learn/responding-to-events)** to learn how to add
## State: a component's memory {/*state-a-components-memory*/}
-Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state.*
+Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *State.*
-You can add state to a component with a [`useState`](/reference/react/useState) Hook. *Hooks* are special functions that let your components use React features (state is one of those features). The `useState` Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
+You can add State to a component with a [`useState`](/reference/react/useState) Hook. *Hooks* are special functions that let your components use React features (State is one of those features). The `useState` Hook lets you declare a State variable. It takes the initial State and returns a pair of values: the current State, and a State setter function that lets you update it.
```js
const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);
```
-Here is how an image gallery uses and updates state on click:
+Here is how an image gallery uses and updates State on click:
@@ -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
@@ -314,11 +314,11 @@ label, textarea { margin-bottom: 10px; display: block; }
-Read **[State as a Snapshot](/learn/state-as-a-snapshot)** to learn why state appears "fixed" and unchanging inside the event handlers.
+Read **[State as a Snapshot](/learn/state-as-a-snapshot)** to learn why State appears "fixed" and unchanging inside the event handlers.
-## Queueing a series of state updates {/*queueing-a-series-of-state-updates*/}
+## Queueing a series of State updates {/*queueing-a-series-of-state-updates*/}
This component is buggy: clicking "+3" increments the score only once.
@@ -354,7 +354,7 @@ button { display: inline-block; margin: 10px; font-size: 20px; }
-[State as a Snapshot](/learn/state-as-a-snapshot) explains why this is happening. Setting state requests a new re-render, but does not change it in the already running code. So `score` continues to be `0` right after you call `setScore(score + 1)`.
+[State as a Snapshot](/learn/state-as-a-snapshot) explains why this is happening. Setting State requests a new re-render, but does not change it in the already running code. So `score` continues to be `0` right after you call `setScore(score + 1)`.
```js
console.log(score); // 0
@@ -366,7 +366,7 @@ setScore(score + 1); // setScore(0 + 1);
console.log(score); // 0
```
-You can fix this by passing an *updater function* when setting state. Notice how replacing `setScore(score + 1)` with `setScore(s => s + 1)` fixes the "+3" button. This lets you queue multiple state updates.
+You can fix this by passing an *updater function* when setting State. Notice how replacing `setScore(score + 1)` with `setScore(s => s + 1)` fixes the "+3" button. This lets you queue multiple State updates.
@@ -402,13 +402,13 @@ button { display: inline-block; margin: 10px; font-size: 20px; }
-Read **[Queueing a Series of State Updates](/learn/queueing-a-series-of-state-updates)** to learn how to queue a sequence of state updates.
+Read **[Queueing a Series of State Updates](/learn/queueing-a-series-of-state-updates)** to learn how to queue a sequence of State updates.
-## Updating objects in state {/*updating-objects-in-state*/}
+## 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:
@@ -637,9 +637,9 @@ Read **[Updating Objects in State](/learn/updating-objects-in-state)** to learn
-## Updating arrays in state {/*updating-arrays-in-state*/}
+## Updating arrays in State {/*updating-arrays-in-state*/}
-Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array:
+Arrays are another type of mutable JavaScript objects you can store in State and should treat as read-only. Just like with objects, when you want to update an array stored in State, you need to create a new one (or make a copy of an existing one), and then set State to use the new array:
diff --git a/src/content/learn/choosing-the-state-structure.md b/src/content/learn/choosing-the-state-structure.md
index 5be2b4d346a..f003eb85bf5 100644
--- a/src/content/learn/choosing-the-state-structure.md
+++ b/src/content/learn/choosing-the-state-structure.md
@@ -4,35 +4,35 @@ title: Choosing the State Structure
-Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. Here are some tips you should consider when structuring state.
+Structuring State well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. Here are some tips you should consider when structuring State.
-* When to use a single vs multiple state variables
-* What to avoid when organizing state
-* How to fix common issues with the state structure
+* When to use a single vs multiple State variables
+* What to avoid when organizing State
+* How to fix common issues with the State structure
-## Principles for structuring state {/*principles-for-structuring-state*/}
+## Principles for structuring State {/*principles-for-structuring-state*/}
-When you write a component that holds some state, you'll have to make choices about how many state variables to use and what the shape of their data should be. While it's possible to write correct programs even with a suboptimal state structure, there are a few principles that can guide you to make better choices:
+When you write a component that holds some State, you'll have to make choices about how many State variables to use and what the shape of their data should be. While it's possible to write correct programs even with a suboptimal State structure, there are a few principles that can guide you to make better choices:
-1. **Group related state.** If you always update two or more state variables at the same time, consider merging them into a single state variable.
-2. **Avoid contradictions in state.** When the state is structured in a way that several pieces of state may contradict and "disagree" with each other, you leave room for mistakes. Try to avoid this.
-3. **Avoid redundant state.** If you can calculate some information from the component's props or its existing state variables during rendering, you should not put that information into that component's state.
-4. **Avoid duplication in state.** When the same data is duplicated between multiple state variables, or within nested objects, it is difficult to keep them in sync. Reduce duplication when you can.
-5. **Avoid deeply nested state.** Deeply hierarchical state is not very convenient to update. When possible, prefer to structure state in a flat way.
+1. **Group related State.** If you always update two or more State variables at the same time, consider merging them into a single State variable.
+2. **Avoid contradictions in State.** When the State is structured in a way that several pieces of State may contradict and "disagree" with each other, you leave room for mistakes. Try to avoid this.
+3. **Avoid redundant State.** If you can calculate some information from the component's props or its existing State variables during rendering, you should not put that information into that component's State.
+4. **Avoid duplication in State.** When the same data is duplicated between multiple State variables, or within nested objects, it is difficult to keep them in sync. Reduce duplication when you can.
+5. **Avoid deeply nested State.** Deeply hierarchical State is not very convenient to update. When possible, prefer to structure State in a flat way.
-The goal behind these principles is to *make state easy to update without introducing mistakes*. Removing redundant and duplicate data from state helps ensure that all its pieces stay in sync. This is similar to how a database engineer might want to ["normalize" the database structure](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description) to reduce the chance of bugs. To paraphrase Albert Einstein, **"Make your state as simple as it can be--but no simpler."**
+The goal behind these principles is to *make State easy to update without introducing mistakes*. Removing redundant and duplicate data from State helps ensure that all its pieces stay in sync. This is similar to how a database engineer might want to ["normalize" the database structure](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description) to reduce the chance of bugs. To paraphrase Albert Einstein, **"Make your State as simple as it can be--but no simpler."**
Now let's see how these principles apply in action.
-## Group related state {/*group-related-state*/}
+## Group related State {/*group-related-state*/}
-You might sometimes be unsure between using a single or multiple state variables.
+You might sometimes be unsure between using a single or multiple State variables.
Should you do this?
@@ -47,7 +47,7 @@ Or this?
const [position, setPosition] = useState({ x: 0, y: 0 });
```
-Technically, you can use either of these approaches. But **if some two state variables always change together, it might be a good idea to unify them into a single state variable.** Then you won't forget to always keep them in sync, like in this example where moving the cursor updates both coordinates of the red dot:
+Technically, you can use either of these approaches. But **if some two State variables always change together, it might be a good idea to unify them into a single State variable.** Then you won't forget to always keep them in sync, like in this example where moving the cursor updates both coordinates of the red dot:
@@ -93,17 +93,17 @@ body { margin: 0; padding: 0; height: 250px; }
-Another case where you'll group data into an object or an array is when you don't know how many pieces of state you'll need. For example, it's helpful when you have a form where the user can add custom fields.
+Another case where you'll group data into an object or an array is when you don't know how many pieces of State you'll need. For example, it's helpful when you have a form where the user can add custom fields.
-If your state variable is an object, remember that [you can't update only one field in it](/learn/updating-objects-in-state) without explicitly copying the other fields. For example, you can't do `setPosition({ x: 100 })` in the above example because it would not have the `y` property at all! Instead, if you wanted to set `x` alone, you would either do `setPosition({ ...position, x: 100 })`, or split them into two state variables and do `setX(100)`.
+If your State variable is an object, remember that [you can't update only one field in it](/learn/updating-objects-in-state) without explicitly copying the other fields. For example, you can't do `setPosition({ x: 100 })` in the above example because it would not have the `y` property at all! Instead, if you wanted to set `x` alone, you would either do `setPosition({ ...position, x: 100 })`, or split them into two State variables and do `setX(100)`.
-## Avoid contradictions in state {/*avoid-contradictions-in-state*/}
+## Avoid contradictions in State {/*avoid-contradictions-in-state*/}
-Here is a hotel feedback form with `isSending` and `isSent` state variables:
+Here is a hotel feedback form with `isSending` and `isSent` State variables:
@@ -157,9 +157,9 @@ function sendMessage(text) {
-While this code works, it leaves the door open for "impossible" states. For example, if you forget to call `setIsSent` and `setIsSending` together, you may end up in a situation where both `isSending` and `isSent` are `true` at the same time. The more complex your component is, the harder it is to understand what happened.
+While this code works, it leaves the door open for "impossible" States. For example, if you forget to call `setIsSent` and `setIsSending` together, you may end up in a situation where both `isSending` and `isSent` are `true` at the same time. The more complex your component is, the harder it is to understand what happened.
-**Since `isSending` and `isSent` should never be `true` at the same time, it is better to replace them with one `status` state variable that may take one of *three* valid states:** `'typing'` (initial), `'sending'`, and `'sent'`:
+**Since `isSending` and `isSent` should never be `true` at the same time, it is better to replace them with one `status` State variable that may take one of *three* valid States:** `'typing'` (initial), `'sending'`, and `'sent'`:
@@ -221,13 +221,13 @@ const isSending = status === 'sending';
const isSent = status === 'sent';
```
-But they're not state variables, so you don't need to worry about them getting out of sync with each other.
+But they're not State variables, so you don't need to worry about them getting out of sync with each other.
-## Avoid redundant state {/*avoid-redundant-state*/}
+## Avoid redundant State {/*avoid-redundant-state*/}
-If you can calculate some information from the component's props or its existing state variables during rendering, you **should not** put that information into that component's state.
+If you can calculate some information from the component's props or its existing State variables during rendering, you **should not** put that information into that component's State.
-For example, take this form. It works, but can you find any redundant state in it?
+For example, take this form. It works, but can you find any redundant State in it?
@@ -280,7 +280,7 @@ label { display: block; margin-bottom: 5px; }
-This form has three state variables: `firstName`, `lastName`, and `fullName`. However, `fullName` is redundant. **You can always calculate `fullName` from `firstName` and `lastName` during render, so remove it from state.**
+This form has three State variables: `firstName`, `lastName`, and `fullName`. However, `fullName` is redundant. **You can always calculate `fullName` from `firstName` and `lastName` during render, so remove it from State.**
This is how you can do it:
@@ -334,7 +334,7 @@ label { display: block; margin-bottom: 5px; }
-Here, `fullName` is *not* a state variable. Instead, it's calculated during render:
+Here, `fullName` is *not* a State variable. Instead, it's calculated during render:
```js
const fullName = firstName + ' ' + lastName;
@@ -344,18 +344,18 @@ As a result, the change handlers don't need to do anything special to update it.
-#### Don't mirror props in state {/*don-t-mirror-props-in-state*/}
+#### Don't mirror props in State {/*don-t-mirror-props-in-state*/}
-A common example of redundant state is code like this:
+A common example of redundant State is code like this:
```js
function Message({ messageColor }) {
const [color, setColor] = useState(messageColor);
```
-Here, a `color` state variable is initialized to the `messageColor` prop. The problem is that **if the parent component passes a different value of `messageColor` later (for example, `'red'` instead of `'blue'`), the `color` *state variable* would not be updated!** The state is only initialized during the first render.
+Here, a `color` State variable is initialized to the `messageColor` prop. The problem is that **if the parent component passes a different value of `messageColor` later (for example, `'red'` instead of `'blue'`), the `color` *State variable* would not be updated!** The State is only initialized during the first render.
-This is why "mirroring" some prop in a state variable can lead to confusion. Instead, use the `messageColor` prop directly in your code. If you want to give it a shorter name, use a constant:
+This is why "mirroring" some prop in a State variable can lead to confusion. Instead, use the `messageColor` prop directly in your code. If you want to give it a shorter name, use a constant:
```js
function Message({ messageColor }) {
@@ -364,18 +364,18 @@ function Message({ messageColor }) {
This way it won't get out of sync with the prop passed from the parent component.
-"Mirroring" props into state only makes sense when you *want* to ignore all updates for a specific prop. By convention, start the prop name with `initial` or `default` to clarify that its new values are ignored:
+"Mirroring" props into State only makes sense when you *want* to ignore all updates for a specific prop. By convention, start the prop name with `initial` or `default` to clarify that its new values are ignored:
```js
function Message({ initialColor }) {
- // The `color` state variable holds the *first* value of `initialColor`.
+ // The `color` State variable holds the *first* value of `initialColor`.
// Further changes to the `initialColor` prop are ignored.
const [color, setColor] = useState(initialColor);
```
-## Avoid duplication in state {/*avoid-duplication-in-state*/}
+## Avoid duplication in State {/*avoid-duplication-in-state*/}
This menu list component lets you choose a single travel snack out of several:
@@ -422,7 +422,7 @@ button { margin-top: 10px; }
-Currently, it stores the selected item as an object in the `selectedItem` state variable. However, this is not great: **the contents of the `selectedItem` is the same object as one of the items inside the `items` list.** This means that the information about the item itself is duplicated in two places.
+Currently, it stores the selected item as an object in the `selectedItem` State variable. However, this is not great: **the contents of the `selectedItem` is the same object as one of the items inside the `items` list.** This means that the information about the item itself is duplicated in two places.
Why is this a problem? Let's make each item editable:
@@ -487,9 +487,9 @@ button { margin-top: 10px; }
-Notice how if you first click "Choose" on an item and *then* edit it, **the input updates but the label at the bottom does not reflect the edits.** This is because you have duplicated state, and you forgot to update `selectedItem`.
+Notice how if you first click "Choose" on an item and *then* edit it, **the input updates but the label at the bottom does not reflect the edits.** This is because you have duplicated State, and you forgot to update `selectedItem`.
-Although you could update `selectedItem` too, an easier fix is to remove duplication. In this example, instead of a `selectedItem` object (which creates a duplication with objects inside `items`), you hold the `selectedId` in state, and *then* get the `selectedItem` by searching the `items` array for an item with that ID:
+Although you could update `selectedItem` too, an easier fix is to remove duplication. In this example, instead of a `selectedItem` object (which creates a duplication with objects inside `items`), you hold the `selectedId` in State, and *then* get the `selectedItem` by searching the `items` array for an item with that ID:
@@ -554,7 +554,7 @@ button { margin-top: 10px; }
-The state used to be duplicated like this:
+The State used to be duplicated like this:
* `items = [{ id: 0, title: 'pretzels'}, ...]`
* `selectedItem = {id: 0, title: 'pretzels'}`
@@ -564,11 +564,11 @@ But after the change it's like this:
* `items = [{ id: 0, title: 'pretzels'}, ...]`
* `selectedId = 0`
-The duplication is gone, and you only keep the essential state!
+The duplication is gone, and you only keep the essential State!
-Now if you edit the *selected* item, the message below will update immediately. This is because `setItems` triggers a re-render, and `items.find(...)` would find the item with the updated title. You didn't need to hold *the selected item* in state, because only the *selected ID* is essential. The rest could be calculated during render.
+Now if you edit the *selected* item, the message below will update immediately. This is because `setItems` triggers a re-render, and `items.find(...)` would find the item with the updated title. You didn't need to hold *the selected item* in State, because only the *selected ID* is essential. The rest could be calculated during render.
-## Avoid deeply nested state {/*avoid-deeply-nested-state*/}
+## Avoid deeply nested State {/*avoid-deeply-nested-state*/}
Imagine a travel plan consisting of planets, continents, and countries. You might be tempted to structure its state using nested objects and arrays, like in this example:
@@ -814,7 +814,7 @@ export const initialTravelPlan = {
Now let's say you want to add a button to delete a place you've already visited. How would you go about it? [Updating nested state](/learn/updating-objects-in-state#updating-a-nested-object) involves making copies of objects all the way up from the part that changed. Deleting a deeply nested place would involve copying its entire parent place chain. Such code can be very verbose.
-**If the state is too nested to update easily, consider making it "flat".** Here is one way you can restructure this data. Instead of a tree-like structure where each `place` has an array of *its child places*, you can have each place hold an array of *its child place IDs*. Then store a mapping from each place ID to the corresponding place.
+**If the State is too nested to update easily, consider making it "flat".** Here is one way you can restructure this data. Instead of a tree-like structure where each `place` has an array of *its child places*, you can have each place hold an array of *its child place IDs*. Then store a mapping from each place ID to the corresponding place.
This data restructuring might remind you of seeing a database table:
@@ -1118,9 +1118,9 @@ export const initialTravelPlan = {
-**Now that the state is "flat" (also known as "normalized"), updating nested items becomes easier.**
+**Now that the State is "flat" (also known as "normalized"), updating nested items becomes easier.**
-In order to remove a place now, you only need to update two levels of state:
+In order to remove a place now, you only need to update two levels of State:
- The updated version of its *parent* place should exclude the removed ID from its `childIds` array.
- The updated version of the root "table" object should include the updated version of the parent place.
@@ -1145,7 +1145,7 @@ export default function TravelPlan() {
childIds: parent.childIds
.filter(id => id !== childId)
};
- // Update the root state object...
+ // Update the root State object...
setPlan({
...plan,
// ...so that it has the updated parent.
@@ -1458,7 +1458,7 @@ button { margin: 10px; }
-You can nest state as much as you like, but making it "flat" can solve numerous problems. It makes state easier to update, and it helps ensure you don't have duplication in different parts of a nested object.
+You can nest State as much as you like, but making it "flat" can solve numerous problems. It makes State easier to update, and it helps ensure you don't have duplication in different parts of a nested object.
@@ -1817,17 +1817,17 @@ button { margin: 10px; }
-Sometimes, you can also reduce state nesting by moving some of the nested state into the child components. This works well for ephemeral UI state that doesn't need to be stored, like whether an item is hovered.
+Sometimes, you can also reduce State nesting by moving some of the nested State into the child components. This works well for ephemeral UI State that doesn't need to be stored, like whether an item is hovered.
-* If two state variables always update together, consider merging them into one.
-* Choose your state variables carefully to avoid creating "impossible" states.
-* Structure your state in a way that reduces the chances that you'll make a mistake updating it.
-* Avoid redundant and duplicate state so that you don't need to keep it in sync.
-* Don't put props *into* state unless you specifically want to prevent updates.
-* For UI patterns like selection, keep ID or index in state instead of the object itself.
-* If updating deeply nested state is complicated, try flattening it.
+* If two State variables always update together, consider merging them into one.
+* Choose your State variables carefully to avoid creating "impossible" States.
+* Structure your State in a way that reduces the chances that you'll make a mistake updating it.
+* Avoid redundant and duplicate State so that you don't need to keep it in sync.
+* Don't put props *into* State unless you specifically want to prevent updates.
+* For UI patterns like selection, keep ID or index in State instead of the object itself.
+* If updating deeply nested State is complicated, try flattening it.
@@ -1890,7 +1890,7 @@ export default function App() {
-The issue is that this component has `color` state initialized with the initial value of the `color` prop. But when the `color` prop changes, this does not affect the state variable! So they get out of sync. To fix this issue, remove the state variable altogether, and use the `color` prop directly.
+The issue is that this component has `color` State initialized with the initial value of the `color` prop. But when the `color` prop changes, this does not affect the State variable! So they get out of sync. To fix this issue, remove the State variable altogether, and use the `color` prop directly.
@@ -2002,7 +2002,7 @@ This packing list has a footer that shows how many items are packed, and how man
-Is any state in this example redundant?
+Is any State in this example redundant?
@@ -2143,7 +2143,7 @@ ul, li { margin: 0; padding: 0; }
-Although you could carefully change each event handler to update the `total` and `packed` counters correctly, the root problem is that these state variables exist at all. They are redundant because you can always calculate the number of items (packed or total) from the `items` array itself. Remove the redundant state to fix the bug:
+Although you could carefully change each event handler to update the `total` and `packed` counters correctly, the root problem is that these State variables exist at all. They are redundant because you can always calculate the number of items (packed or total) from the `items` array itself. Remove the redundant State to fix the bug:
@@ -2282,7 +2282,7 @@ Notice how the event handlers are only concerned with calling `setItems` after t
#### Fix the disappearing selection {/*fix-the-disappearing-selection*/}
-There is a list of `letters` in state. When you hover or focus a particular letter, it gets highlighted. The currently highlighted letter is stored in the `highlightedLetter` state variable. You can "star" and "unstar" individual letters, which updates the `letters` array in state.
+There is a list of `letters` in State. When you hover or focus a particular letter, it gets highlighted. The currently highlighted letter is stored in the `highlightedLetter` State variable. You can "star" and "unstar" individual letters, which updates the `letters` array in State.
This code works, but there is a minor UI glitch. When you press "Star" or "Unstar", the highlighting disappears for a moment. However, it reappears as soon as you move your pointer or switch to another letter with keyboard. Why is this happening? Fix it so that the highlighting doesn't disappear after the button click.
@@ -2391,9 +2391,9 @@ li { border-radius: 5px; }
-The problem is that you're holding the letter object in `highlightedLetter`. But you're also holding the same information in the `letters` array. So your state has duplication! When you update the `letters` array after the button click, you create a new letter object which is different from `highlightedLetter`. This is why `highlightedLetter === letter` check becomes `false`, and the highlight disappears. It reappears the next time you call `setHighlightedLetter` when the pointer moves.
+The problem is that you're holding the letter object in `highlightedLetter`. But you're also holding the same information in the `letters` array. So your State has duplication! When you update the `letters` array after the button click, you create a new letter object which is different from `highlightedLetter`. This is why `highlightedLetter === letter` check becomes `false`, and the highlight disappears. It reappears the next time you call `setHighlightedLetter` when the pointer moves.
-To fix the issue, remove the duplication from state. Instead of storing *the letter itself* in two places, store the `highlightedId` instead. Then you can check `isHighlighted` for each letter with `letter.id === highlightedId`, which will work even if the `letter` object has changed since the last render.
+To fix the issue, remove the duplication from State. Instead of storing *the letter itself* in two places, store the `highlightedId` instead. Then you can check `isHighlighted` for each letter with `letter.id === highlightedId`, which will work even if the `letter` object has changed since the last render.
@@ -2502,13 +2502,13 @@ li { border-radius: 5px; }
#### Implement multiple selection {/*implement-multiple-selection*/}
-In this example, each `Letter` has an `isSelected` prop and an `onToggle` handler that marks it as selected. This works, but the state is stored as a `selectedId` (either `null` or an ID), so only one letter can get selected at any given time.
+In this example, each `Letter` has an `isSelected` prop and an `onToggle` handler that marks it as selected. This works, but the State is stored as a `selectedId` (either `null` or an ID), so only one letter can get selected at any given time.
-Change the state structure to support multiple selection. (How would you structure it? Think about this before writing the code.) Each checkbox should become independent from the others. Clicking a selected letter should uncheck it. Finally, the footer should show the correct number of the selected items.
+Change the State structure to support multiple selection. (How would you structure it? Think about this before writing the code.) Each checkbox should become independent from the others. Clicking a selected letter should uncheck it. Finally, the footer should show the correct number of the selected items.
-Instead of a single selected ID, you might want to hold an array or a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) of selected IDs in state.
+Instead of a single selected ID, you might want to hold an array or a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) of selected IDs in State.
@@ -2609,7 +2609,7 @@ label { width: 100%; padding: 5px; display: inline-block; }
-Instead of a single `selectedId`, keep a `selectedIds` *array* in state. For example, if you select the first and the last letter, it would contain `[0, 2]`. When nothing is selected, it would be an empty `[]` array:
+Instead of a single `selectedId`, keep a `selectedIds` *array* in State. For example, if you select the first and the last letter, it would contain `[0, 2]`. When nothing is selected, it would be an empty `[]` array:
@@ -2717,7 +2717,7 @@ label { width: 100%; padding: 5px; display: inline-block; }
One minor downside of using an array is that for each item, you're calling `selectedIds.includes(letter.id)` to check whether it's selected. If the array is very large, this can become a performance problem because array search with [`includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) takes linear time, and you're doing this search for each individual item.
-To fix this, you can hold a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) in state instead, which provides a fast [`has()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has) operation:
+To fix this, you can hold a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) in State instead, which provides a fast [`has()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has) operation:
@@ -2822,7 +2822,7 @@ label { width: 100%; padding: 5px; display: inline-block; }
Now each item does a `selectedIds.has(letter.id)` check, which is very fast.
-Keep in mind that you [should not mutate objects in state](/learn/updating-objects-in-state), and that includes Sets, too. This is why the `handleToggle` function creates a *copy* of the Set first, and then updates that copy.
+Keep in mind that you [should not mutate objects in State](/learn/updating-objects-in-state), and that includes Sets, too. This is why the `handleToggle` function creates a *copy* of the Set first, and then updates that copy.
diff --git a/src/content/learn/escape-hatches.md b/src/content/learn/escape-hatches.md
index 23f11f54e28..7e76e5661a6 100644
--- a/src/content/learn/escape-hatches.md
+++ b/src/content/learn/escape-hatches.md
@@ -29,7 +29,7 @@ When you want a component to "remember" some information, but you don't want tha
const ref = useRef(0);
```
-Like state, refs are retained by React between re-renders. However, setting state re-renders a component. Changing a ref does not! You can access the current value of that ref through the `ref.current` property.
+Like State, refs are retained by React between re-renders. However, setting State re-renders a component. Changing a ref does not! You can access the current value of that ref through the `ref.current` property.
@@ -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:
@@ -199,7 +199,7 @@ There are two common cases in which you don't need Effects:
- **You don't need Effects to transform data for rendering.**
- **You don't need Effects to handle user events.**
-For example, you don't need an Effect to adjust some state based on other state:
+For example, you don't need an Effect to adjust some State based on other State:
```js {5-9}
function Form() {
@@ -318,7 +318,7 @@ This section describes an **experimental API that has not yet been released** in
-Event handlers only re-run when you perform the same interaction again. Unlike event handlers, Effects re-synchronize if any of the values they read, like props or state, are different than during last render. Sometimes, you want a mix of both behaviors: an Effect that re-runs in response to some values but not others.
+Event handlers only re-run when you perform the same interaction again. Unlike event handlers, Effects re-synchronize if any of the values they read, like props or State, are different than during last render. Sometimes, you want a mix of both behaviors: an Effect that re-runs in response to some values but not others.
All code inside Effects is *reactive.* It will run again if some reactive value it reads has changed due to a re-render. For example, this Effect will re-connect to the chat if either `roomId` or `theme` have changed:
@@ -591,7 +591,7 @@ Read **[Separating Events from Effects](/learn/separating-events-from-effects)**
## Removing Effect dependencies {/*removing-effect-dependencies*/}
-When you write an Effect, the linter will verify that you've included every reactive value (like props and state) that the Effect reads in the list of your Effect's dependencies. This ensures that your Effect remains synchronized with the latest props and state of your component. Unnecessary dependencies may cause your Effect to run too often, or even create an infinite loop. The way you remove them depends on the case.
+When you write an Effect, the linter will verify that you've included every reactive value (like props and tate) that the Effect reads in the list of your Effect's dependencies. This ensures that your Effect remains synchronized with the latest props and State of your component. Unnecessary dependencies may cause your Effect to run too often, or even create an infinite loop. The way you remove them depends on the case.
For example, this Effect depends on the `options` object which gets re-created every time you edit the input:
diff --git a/src/content/learn/extracting-state-logic-into-a-reducer.md b/src/content/learn/extracting-state-logic-into-a-reducer.md
index 5c08c012390..f6e7d9aaba5 100644
--- a/src/content/learn/extracting-state-logic-into-a-reducer.md
+++ b/src/content/learn/extracting-state-logic-into-a-reducer.md
@@ -4,7 +4,7 @@ title: Extracting State Logic into a Reducer
-Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called a _reducer._
+Components with many State updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the State update logic outside your component in a single function, called a _reducer._
@@ -17,9 +17,9 @@ Components with many state updates spread across many event handlers can get ove
-## Consolidate state logic with a reducer {/*consolidate-state-logic-with-a-reducer*/}
+## Consolidate State logic with a reducer {/*consolidate-state-logic-with-a-reducer*/}
-As your components grow in complexity, it can get harder to see at a glance all the different ways in which a component's state gets updated. For example, the `TaskApp` component below holds an array of `tasks` in state and uses three different event handlers to add, remove, and edit tasks:
+As your components grow in complexity, it can get harder to see at a glance all the different ways in which a component's state gets updated. For example, the `TaskApp` component below holds an array of `tasks` in State and uses three different event handlers to add, remove, and edit tasks:
@@ -179,17 +179,17 @@ li {
-Each of its event handlers calls `setTasks` in order to update the state. As this component grows, so does the amount of state logic sprinkled throughout it. To reduce this complexity and keep all your logic in one easy-to-access place, you can move that state logic into a single function outside your component, **called a "reducer".**
+Each of its event handlers calls `setTasks` in order to update the State. As this component grows, so does the amount of State logic sprinkled throughout it. To reduce this complexity and keep all your logic in one easy-to-access place, you can move that State logic into a single function outside your component, **called a "reducer".**
-Reducers are a different way to handle state. You can migrate from `useState` to `useReducer` in three steps:
+Reducers are a different way to handle State. You can migrate from `useState` to `useReducer` in three steps:
-1. **Move** from setting state to dispatching actions.
+1. **Move** from setting State to dispatching actions.
2. **Write** a reducer function.
3. **Use** the reducer from your component.
-### Step 1: Move from setting state to dispatching actions {/*step-1-move-from-setting-state-to-dispatching-actions*/}
+### Step 1: Move from setting State to dispatching actions {/*step-1-move-from-setting-state-to-dispatching-actions*/}
-Your event handlers currently specify _what to do_ by setting state:
+Your event handlers currently specify _what to do_ by setting State:
```js
function handleAddTask(text) {
@@ -220,13 +220,13 @@ function handleDeleteTask(taskId) {
}
```
-Remove all the state setting logic. What you are left with are three event handlers:
+Remove all the State setting logic. What you are left with are three event handlers:
- `handleAddTask(text)` is called when the user presses "Add".
- `handleChangeTask(task)` is called when the user toggles a task or presses "Save".
- `handleDeleteTask(taskId)` is called when the user presses "Delete".
-Managing state with reducers is slightly different from directly setting state. Instead of telling React "what to do" by setting state, you specify "what the user just did" by dispatching "actions" from your event handlers. (The state update logic will live elsewhere!) So instead of "setting `tasks`" via an event handler, you're dispatching an "added/changed/deleted a task" action. This is more descriptive of the user's intent.
+Managing State with reducers is slightly different from directly setting State. Instead of telling React "what to do" by setting State, you specify "what the user just did" by dispatching "actions" from your event handlers. (The State update logic will live elsewhere!) So instead of "setting `tasks`" via an event handler, you're dispatching an "added/changed/deleted a task" action. This is more descriptive of the user's intent.
```js
function handleAddTask(text) {
@@ -286,23 +286,23 @@ dispatch({
### Step 2: Write a reducer function {/*step-2-write-a-reducer-function*/}
-A reducer function is where you will put your state logic. It takes two arguments, the current state and the action object, and it returns the next state:
+A reducer function is where you will put your State logic. It takes two arguments, the current State and the action object, and it returns the next State:
```js
function yourReducer(state, action) {
- // return next state for React to set
+ // return next State for React to set
}
```
-React will set the state to what you return from the reducer.
+React will set the State to what you return from the reducer.
-To move your state setting logic from your event handlers to a reducer function in this example, you will:
+To move your State setting logic from your event handlers to a reducer function in this example, you will:
-1. Declare the current state (`tasks`) as the first argument.
+1. Declare the current State (`tasks`) as the first argument.
2. Declare the `action` object as the second argument.
-3. Return the _next_ state from the reducer (which React will set the state to).
+3. Return the _next_ State from the reducer (which React will set the State to).
-Here is all the state setting logic migrated to a reducer function:
+Here is all the State setting logic migrated to a reducer function:
```js
function tasksReducer(tasks, action) {
@@ -331,7 +331,7 @@ function tasksReducer(tasks, action) {
}
```
-Because the reducer function takes state (`tasks`) as an argument, you can **declare it outside of your component.** This decreases the indentation level and can make your code easier to read.
+Because the reducer function takes State (`tasks`) as an argument, you can **declare it outside of your component.** This decreases the indentation level and can make your code easier to read.
@@ -392,9 +392,9 @@ const sum = arr.reduce(
); // 1 + 2 + 3 + 4 + 5
```
-The function you pass to `reduce` is known as a "reducer". It takes the _result so far_ and the _current item,_ then it returns the _next result._ React reducers are an example of the same idea: they take the _state so far_ and the _action_, and return the _next state._ In this way, they accumulate actions over time into state.
+The function you pass to `reduce` is known as a "reducer". It takes the _result so far_ and the _current item,_ then it returns the _next result._ React reducers are an example of the same idea: they take the _state so far_ and the _action_, and return the _next state._ In this way, they accumulate actions over time into State.
-You could even use the `reduce()` method with an `initialState` and an array of `actions` to calculate the final state by passing your reducer function to it:
+You could even use the `reduce()` method with an `initialState` and an array of `actions` to calculate the final State by passing your reducer function to it:
@@ -477,12 +477,12 @@ with `useReducer` like so:
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
```
-The `useReducer` Hook is similar to `useState`—you must pass it an initial state and it returns a stateful value and a way to set state (in this case, the dispatch function). But it's a little different.
+The `useReducer` Hook is similar to `useState`—you must pass it an initial State and it returns a stateful value and a way to set State (in this case, the dispatch function). But it's a little different.
The `useReducer` Hook takes two arguments:
1. A reducer function
-2. An initial state
+2. An initial State
And it returns:
@@ -862,19 +862,19 @@ li {
-Component logic can be easier to read when you separate concerns like this. Now the event handlers only specify _what happened_ by dispatching actions, and the reducer function determines _how the state updates_ in response to them.
+Component logic can be easier to read when you separate concerns like this. Now the event handlers only specify _what happened_ by dispatching actions, and the reducer function determines _how the State updates_ in response to them.
## Comparing `useState` and `useReducer` {/*comparing-usestate-and-usereducer*/}
Reducers are not without downsides! Here's a few ways you can compare them:
-- **Code size:** Generally, with `useState` you have to write less code upfront. With `useReducer`, you have to write both a reducer function _and_ dispatch actions. However, `useReducer` can help cut down on the code if many event handlers modify state in a similar way.
-- **Readability:** `useState` is very easy to read when the state updates are simple. When they get more complex, they can bloat your component's code and make it difficult to scan. In this case, `useReducer` lets you cleanly separate the _how_ of update logic from the _what happened_ of event handlers.
-- **Debugging:** When you have a bug with `useState`, it can be difficult to tell _where_ the state was set incorrectly, and _why_. With `useReducer`, you can add a console log into your reducer to see every state update, and _why_ it happened (due to which `action`). If each `action` is correct, you'll know that the mistake is in the reducer logic itself. However, you have to step through more code than with `useState`.
-- **Testing:** A reducer is a pure function that doesn't depend on your component. This means that you can export and test it separately in isolation. While generally it's best to test components in a more realistic environment, for complex state update logic it can be useful to assert that your reducer returns a particular state for a particular initial state and action.
+- **Code size:** Generally, with `useState` you have to write less code upfront. With `useReducer`, you have to write both a reducer function _and_ dispatch actions. However, `useReducer` can help cut down on the code if many event handlers modify State in a similar way.
+- **Readability:** `useState` is very easy to read when the State updates are simple. When they get more complex, they can bloat your component's code and make it difficult to scan. In this case, `useReducer` lets you cleanly separate the _how_ of update logic from the _what happened_ of event handlers.
+- **Debugging:** When you have a bug with `useState`, it can be difficult to tell _where_ the State was set incorrectly, and _why_. With `useReducer`, you can add a console log into your reducer to see every State update, and _why_ it happened (due to which `action`). If each `action` is correct, you'll know that the mistake is in the reducer logic itself. However, you have to step through more code than with `useState`.
+- **Testing:** A reducer is a pure function that doesn't depend on your component. This means that you can export and test it separately in isolation. While generally it's best to test components in a more realistic environment, for complex State update logic it can be useful to assert that your reducer returns a particular State for a particular initial State and action.
- **Personal preference:** Some people like reducers, others don't. That's okay. It's a matter of preference. You can always convert between `useState` and `useReducer` back and forth: they are equivalent!
-We recommend using a reducer if you often encounter bugs due to incorrect state updates in some component, and want to introduce more structure to its code. You don't have to use reducers for everything: feel free to mix and match! You can even `useState` and `useReducer` in the same component.
+We recommend using a reducer if you often encounter bugs due to incorrect State updates in some component, and want to introduce more structure to its code. You don't have to use reducers for everything: feel free to mix and match! You can even `useState` and `useReducer` in the same component.
## Writing reducers well {/*writing-reducers-well*/}
@@ -1082,13 +1082,13 @@ li {
-Reducers must be pure, so they shouldn't mutate state. But Immer provides you with a special `draft` object which is safe to mutate. Under the hood, Immer will create a copy of your state with the changes you made to the `draft`. This is why reducers managed by `useImmerReducer` can mutate their first argument and don't need to return state.
+Reducers must be pure, so they shouldn't mutate State. But Immer provides you with a special `draft` object which is safe to mutate. Under the hood, Immer will create a copy of your State with the changes you made to the `draft`. This is why reducers managed by `useImmerReducer` can mutate their first argument and don't need to return State.
- To convert from `useState` to `useReducer`:
1. Dispatch actions from event handlers.
- 2. Write a reducer function that returns the next state for a given state and action.
+ 2. Write a reducer function that returns the next State for a given State and action.
3. Replace `useState` with `useReducer`.
- Reducers require you to write a bit more code, but they help with debugging and testing.
- Reducers must be pure.
@@ -1854,9 +1854,9 @@ textarea {
-The resulting behavior is the same. But keep in mind that action types should ideally describe "what the user did" rather than "how you want the state to change". This makes it easier to later add more features.
+The resulting behavior is the same. But keep in mind that action types should ideally describe "what the user did" rather than "how you want the State to change". This makes it easier to later add more features.
-With either solution, it's important that you **don't** place the `alert` inside a reducer. The reducer should be a pure function--it should only calculate the next state. It should not "do" anything, including displaying messages to the user. That should happen in the event handler. (To help catch mistakes like this, React will call your reducers multiple times in Strict Mode. This is why, if you put an alert in a reducer, it fires twice.)
+With either solution, it's important that you **don't** place the `alert` inside a reducer. The reducer should be a pure function--it should only calculate the next State. It should not "do" anything, including displaying messages to the user. That should happen in the event handler. (To help catch mistakes like this, React will call your reducers multiple times in Strict Mode. This is why, if you put an alert in a reducer, it fires twice.)
@@ -1875,11 +1875,11 @@ case 'changed_selection': {
This is because you don't want to share a single message draft between several recipients. But it would be better if your app "remembered" a draft for each contact separately, restoring them when you switch contacts.
-Your task is to change the way the state is structured so that you remember a separate message draft _per contact_. You would need to make a few changes to the reducer, the initial state, and the components.
+Your task is to change the way the State is structured so that you remember a separate message draft _per contact_. You would need to make a few changes to the reducer, the initial State, and the components.
-You can structure your state like this:
+You can structure your State like this:
```js
export const initialState = {
@@ -2237,7 +2237,7 @@ textarea {
-Notably, you didn't need to change any of the event handlers to implement this different behavior. Without a reducer, you would have to change every event handler that updates the state.
+Notably, you didn't need to change any of the event handlers to implement this different behavior. Without a reducer, you would have to change every event handler that updates the State.
@@ -2263,7 +2263,7 @@ export function useReducer(reducer, initialState) {
}
```
-Recall that a reducer function takes two arguments--the current state and the action object--and it returns the next state. What should your `dispatch` implementation do with it?
+Recall that a reducer function takes two arguments--the current State and the action object--and it returns the next State. What should your `dispatch` implementation do with it?
@@ -2439,7 +2439,7 @@ textarea {
-Dispatching an action calls a reducer with the current state and the action, and stores the result as the next state. This is what it looks like in code:
+Dispatching an action calls a reducer with the current State and the action, and stores the result as the next State. This is what it looks like in code:
diff --git a/src/content/learn/index.md b/src/content/learn/index.md
index b57655bc426..feb792351b2 100644
--- a/src/content/learn/index.md
+++ b/src/content/learn/index.md
@@ -300,7 +300,7 @@ Notice how `onClick={handleClick}` has no parentheses at the end! Do not _call_
## Updating the screen {/*updating-the-screen*/}
-Often, you'll want your component to "remember" some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add *state* to your component.
+Often, you'll want your component to "remember" some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add *State* to your component.
First, import [`useState`](/reference/react/useState) from React:
@@ -308,7 +308,7 @@ First, import [`useState`](/reference/react/useState) from React:
import { useState } from 'react';
```
-Now you can declare a *state variable* inside your component:
+Now you can declare a *State variable* inside your component:
```js
function MyButton() {
@@ -316,9 +316,9 @@ function MyButton() {
// ...
```
-You’ll get two things from `useState`: the current state (`count`), and the function that lets you update it (`setCount`). You can give them any names, but the convention is to write `[something, setSomething]`.
+You’ll get two things from `useState`: the current State (`count`), and the function that lets you update it (`setCount`). You can give them any names, but the convention is to write `[something, setSomething]`.
-The first time the button is displayed, `count` will be `0` because you passed `0` to `useState()`. When you want to change state, call `setCount()` and pass the new value to it. Clicking this button will increment the counter:
+The first time the button is displayed, `count` will be `0` because you passed `0` to `useState()`. When you want to change State, call `setCount()` and pass the new value to it. Clicking this button will increment the counter:
```js {5}
function MyButton() {
@@ -338,7 +338,7 @@ function MyButton() {
React will call your component function again. This time, `count` will be `1`. Then it will be `2`. And so on.
-If you render the same component multiple times, each will get its own state. Click each button separately:
+If you render the same component multiple times, each will get its own State. Click each button separately:
@@ -379,7 +379,7 @@ button {
-Notice how each button "remembers" its own `count` state and doesn't affect other buttons.
+Notice how each button "remembers" its own `count` State and doesn't affect other buttons.
## Using Hooks {/*using-hooks*/}
@@ -395,7 +395,7 @@ In the previous example, each `MyButton` had its own independent `count`, and wh
-Initially, each `MyButton`'s `count` state is `0`
+Initially, each `MyButton`'s `count` State is `0`
@@ -409,7 +409,7 @@ The first `MyButton` updates its `count` to `1`
However, often you'll need components to *share data and always update together*.
-To make both `MyButton` components display the same `count` and update together, you need to move the state from the individual buttons "upwards" to the closest component containing all of them.
+To make both `MyButton` components display the same `count` and update together, you need to move the State from the individual buttons "upwards" to the closest component containing all of them.
In this example, it is `MyApp`:
@@ -417,13 +417,13 @@ In this example, it is `MyApp`:
-Initially, `MyApp`'s `count` state is `0` and is passed down to both children
+Initially, `MyApp`'s `count` State is `0` and is passed down to both children
-On click, `MyApp` updates its `count` state to `1` and passes it down to both children
+On click, `MyApp` updates its `count` State to `1` and passes it down to both children
@@ -431,7 +431,7 @@ On click, `MyApp` updates its `count` state to `1` and passes it down to both ch
Now when you click either button, the `count` in `MyApp` will change, which will change both of the counts in `MyButton`. Here's how you can express this in code.
-First, *move the state up* from `MyButton` into `MyApp`:
+First, *move the State up* from `MyButton` into `MyApp`:
```js {2-6,18}
export default function MyApp() {
@@ -456,7 +456,7 @@ function MyButton() {
```
-Then, *pass the state down* from `MyApp` to each `MyButton`, together with the shared click handler. You can pass information to `MyButton` using the JSX curly braces, just like you previously did with built-in tags like ``:
+Then, *pass the State down* from `MyApp` to each `MyButton`, together with the shared click handler. You can pass information to `MyButton` using the JSX curly braces, just like you previously did with built-in tags like ``:
```js {11-12}
export default function MyApp() {
@@ -476,7 +476,7 @@ export default function MyApp() {
}
```
-The information you pass down like this is called _props_. Now the `MyApp` component contains the `count` state and the `handleClick` event handler, and *passes both of them down as props* to each of the buttons.
+The information you pass down like this is called _props_. Now the `MyApp` component contains the `count` State and the `handleClick` event handler, and *passes both of them down as props* to each of the buttons.
Finally, change `MyButton` to *read* the props you have passed from its parent component:
@@ -490,7 +490,7 @@ function MyButton({ count, onClick }) {
}
```
-When you click the button, the `onClick` handler fires. Each button's `onClick` prop was set to the `handleClick` function inside `MyApp`, so the code inside of it runs. That code calls `setCount(count + 1)`, incrementing the `count` state variable. The new `count` value is passed as a prop to each button, so they all show the new value. This is called "lifting state up". By moving state up, you've shared it between components.
+When you click the button, the `onClick` handler fires. Each button's `onClick` prop was set to the `handleClick` function inside `MyApp`, so the code inside of it runs. That code calls `setCount(count + 1)`, incrementing the `count` State variable. The new `count` value is passed as a prop to each button, so they all show the new value. This is called "lifting State up". By moving State up, you've shared it between components.
diff --git a/src/content/learn/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md
index 6d4f55763fa..707aa38f713 100644
--- a/src/content/learn/keeping-components-pure.md
+++ b/src/content/learn/keeping-components-pure.md
@@ -219,7 +219,7 @@ Every new React feature we're building takes advantage of purity. From data fetc
* **It minds its own business.** It should not change any objects or variables that existed before rendering.
* **Same inputs, same output.** Given the same inputs, a component should always return the same JSX.
* Rendering can happen at any time, so components should not depend on each others' rendering sequence.
-* You should not mutate any of the inputs that your components use for rendering. That includes props, state, and context. To update the screen, ["set" state](/learn/state-a-components-memory) instead of mutating preexisting objects.
+* You should not mutate any of the inputs that your components use for rendering. That includes props, State, and context. To update the screen, ["set" state](/learn/state-a-components-memory) instead of mutating preexisting objects.
* Strive to express your component's logic in the JSX you return. When you need to "change things", you'll usually want to do it in an event handler. As a last resort, you can `useEffect`.
* Writing pure functions takes a bit of practice, but it unlocks the power of React's paradigm.
diff --git a/src/content/learn/lifecycle-of-reactive-effects.md b/src/content/learn/lifecycle-of-reactive-effects.md
index 3dc9a75f02b..4079fb9631a 100644
--- a/src/content/learn/lifecycle-of-reactive-effects.md
+++ b/src/content/learn/lifecycle-of-reactive-effects.md
@@ -4,7 +4,7 @@ title: 'Lifecycle of Reactive Effects'
-Effects have a different lifecycle from components. Components may mount, update, or unmount. An Effect can only do two things: to start synchronizing something, and later to stop synchronizing it. This cycle can happen multiple times if your Effect depends on props and state that change over time. React provides a linter rule to check that you've specified your Effect's dependencies correctly. This keeps your Effect synchronized to the latest props and state.
+Effects have a different lifecycle from components. Components may mount, update, or unmount. An Effect can only do two things: to start synchronizing something, and later to stop synchronizing it. This cycle can happen multiple times if your Effect depends on props and State that change over time. React provides a linter rule to check that you've specified your Effect's dependencies correctly. This keeps your Effect synchronized to the latest props and State.
@@ -26,10 +26,10 @@ Effects have a different lifecycle from components. Components may mount, update
Every React component goes through the same lifecycle:
- A component _mounts_ when it's added to the screen.
-- A component _updates_ when it receives new props or state, usually in response to an interaction.
+- A component _updates_ when it receives new props or State, usually in response to an interaction.
- A component _unmounts_ when it's removed from the screen.
-**It's a good way to think about components, but _not_ about Effects.** Instead, try to think about each Effect independently from your component's lifecycle. An Effect describes how to [synchronize an external system](/learn/synchronizing-with-effects) to the current props and state. As your code changes, synchronization will need to happen more or less often.
+**It's a good way to think about components, but _not_ about Effects.** Instead, try to think about each Effect independently from your component's lifecycle. An Effect describes how to [synchronize an external system](/learn/synchronizing-with-effects) to the current props and State. As your code changes, synchronization will need to happen more or less often.
To illustrate this point, consider this Effect connecting your component to a chat server:
@@ -127,7 +127,7 @@ At this point, you want React to do two things:
1. Stop synchronizing with the old `roomId` (disconnect from the `"general"` room)
2. Start synchronizing with the new `roomId` (connect to the `"travel"` room)
-**Luckily, you've already taught React how to do both of these things!** Your Effect's body specifies how to start synchronizing, and your cleanup function specifies how to stop synchronizing. All that React needs to do now is to call them in the correct order and with the correct props and state. Let's see how exactly that happens.
+**Luckily, you've already taught React how to do both of these things!** Your Effect's body specifies how to start synchronizing, and your cleanup function specifies how to stop synchronizing. All that React needs to do now is to call them in the correct order and with the correct props and State. Let's see how exactly that happens.
### How React re-synchronizes your Effect {/*how-react-re-synchronizes-your-effect*/}
@@ -373,21 +373,21 @@ Why doesn't `serverUrl` need to be a dependency?
This is because the `serverUrl` never changes due to a re-render. It's always the same no matter how many times the component re-renders and why. Since `serverUrl` never changes, it wouldn't make sense to specify it as a dependency. After all, dependencies only do something when they change over time!
-On the other hand, `roomId` may be different on a re-render. **Props, state, and other values declared inside the component are _reactive_ because they're calculated during rendering and participate in the React data flow.**
+On the other hand, `roomId` may be different on a re-render. **Props, State, and other values declared inside the component are _reactive_ because they're calculated during rendering and participate in the React data flow.**
-If `serverUrl` was a state variable, it would be reactive. Reactive values must be included in dependencies:
+If `serverUrl` was a State variable, it would be reactive. Reactive values must be included in dependencies:
```js {2,5,10}
function ChatRoom({ roomId }) { // Props change over time
const [serverUrl, setServerUrl] = useState('https://localhost:1234'); // State may change over time
useEffect(() => {
- const connection = createConnection(serverUrl, roomId); // Your Effect reads props and state
+ const connection = createConnection(serverUrl, roomId); // Your Effect reads props and State
connection.connect();
return () => {
connection.disconnect();
};
- }, [roomId, serverUrl]); // So you tell React that this Effect "depends on" on props and state
+ }, [roomId, serverUrl]); // So you tell React that this Effect "depends on" on props and State
// ...
}
```
@@ -552,9 +552,9 @@ However, if you [think from the Effect's perspective,](#thinking-from-the-effect
### All variables declared in the component body are reactive {/*all-variables-declared-in-the-component-body-are-reactive*/}
-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.
+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
@@ -571,9 +571,9 @@ function ChatRoom({ roomId, selectedServerUrl }) { // roomId is reactive
}
```
-In this example, `serverUrl` is not a prop or a state variable. It's a regular variable that you calculate during rendering. But it's calculated during rendering, so it can change due to a re-render. This is why it's reactive.
+In this example, `serverUrl` is not a prop or a State variable. It's a regular variable that you calculate during rendering. But it's calculated during rendering, so it can change due to a re-render. This is why it's reactive.
-**All values inside the component (including props, state, and variables in your component's body) are reactive. Any reactive value can change on a re-render, so you need to include reactive values as Effect's dependencies.**
+**All values inside the component (including props, State, and variables in your component's body) are reactive. Any reactive value can change on a re-render, so you need to include reactive values as Effect's dependencies.**
In other words, Effects "react" to all values from the component body.
@@ -738,7 +738,7 @@ function ChatRoom() {
* **Check that your Effect represents an independent synchronization process.** If your Effect doesn't synchronize anything, [it might be unnecessary.](/learn/you-might-not-need-an-effect) If it synchronizes several independent things, [split it up.](#each-effect-represents-a-separate-synchronization-process)
-* **If you want to read the latest value of props or state without "reacting" to it and re-synchronizing the Effect,** you can split your Effect into a reactive part (which you'll keep in the Effect) and a non-reactive part (which you'll extract into something called an _Effect Event_). [Read about separating Events from Effects.](/learn/separating-events-from-effects)
+* **If you want to read the latest value of props or State without "reacting" to it and re-synchronizing the Effect,** you can split your Effect into a reactive part (which you'll keep in the Effect) and a non-reactive part (which you'll extract into something called an _Effect Event_). [Read about separating Events from Effects.](/learn/separating-events-from-effects)
* **Avoid relying on objects and functions as dependencies.** If you create objects and functions during rendering and then read them from an Effect, they will be different on every render. This will cause your Effect to re-synchronize every time. [Read more about removing unnecessary dependencies from Effects.](/learn/removing-effect-dependencies)
@@ -939,7 +939,7 @@ button { margin-left: 10px; }
In this example, an Effect subscribes to the window [`pointermove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointermove_event) event to move a pink dot on the screen. Try hovering over the preview area (or touching the screen if you're on a mobile device), and see how the pink dot follows your movement.
-There is also a checkbox. Ticking the checkbox toggles the `canMove` state variable, but this state variable is not used anywhere in the code. Your task is to change the code so that when `canMove` is `false` (the checkbox is ticked off), the dot should stop moving. After you toggle the checkbox back on (and set `canMove` to `true`), the box should follow the movement again. In other words, whether the dot can move or not should stay synchronized to whether the checkbox is checked.
+There is also a checkbox. Ticking the checkbox toggles the `canMove` State variable, but this State variable is not used anywhere in the code. Your task is to change the code so that when `canMove` is `false` (the checkbox is ticked off), the dot should stop moving. After you toggle the checkbox back on (and set `canMove` to `true`), the box should follow the movement again. In other words, whether the dot can move or not should stay synchronized to whether the checkbox is checked.
@@ -1119,9 +1119,9 @@ In both of these cases, `canMove` is a reactive variable that you read inside th
#### Investigate a stale value bug {/*investigate-a-stale-value-bug*/}
-In this example, the pink dot should move when the checkbox is on, and should stop moving when the checkbox is off. The logic for this has already been implemented: the `handleMove` event handler checks the `canMove` state variable.
+In this example, the pink dot should move when the checkbox is on, and should stop moving when the checkbox is off. The logic for this has already been implemented: the `handleMove` event handler checks the `canMove` State variable.
-However, for some reason, the `canMove` state variable inside `handleMove` appears to be "stale": it's always `true`, even after you tick off the checkbox. How is this possible? Find the mistake in the code and fix it.
+However, for some reason, the `canMove` State variable inside `handleMove` appears to be "stale": it's always `true`, even after you tick off the checkbox. How is this possible? Find the mistake in the code and fix it.
@@ -1621,7 +1621,7 @@ In this version, the `App` component passes a boolean prop instead of a function
In this example, there are two select boxes. One select box lets the user pick a planet. Another select box lets the user pick a place *on that planet.* The second box doesn't work yet. Your task is to make it show the places on the chosen planet.
-Look at how the first select box works. It populates the `planetList` state with the result from the `"/planets"` API call. The currently selected planet's ID is kept in the `planetId` state variable. You need to find where to add some additional code so that the `placeList` state variable is populated with the result of the `"/planets/" + planetId + "/places"` API call.
+Look at how the first select box works. It populates the `planetList` State with the result from the `"/planets"` API call. The currently selected planet's ID is kept in the `planetId` State variable. You need to find where to add some additional code so that the `placeList` State variable is populated with the result of the `"/planets/" + planetId + "/places"` API call.
If you implement this right, selecting a planet should populate the place list. Changing a planet should change the place list.
diff --git a/src/content/learn/managing-state.md b/src/content/learn/managing-state.md
index 93bcc10fd61..350e624bd30 100644
--- a/src/content/learn/managing-state.md
+++ b/src/content/learn/managing-state.md
@@ -4,27 +4,27 @@ title: Managing State
-As your application grows, it helps to be more intentional about how your state is organized and how the data flows between your components. Redundant or duplicate state is a common source of bugs. In this chapter, you'll learn how to structure your state well, how to keep your state update logic maintainable, and how to share state between distant components.
+As your application grows, it helps to be more intentional about how your State is organized and how the data flows between your components. Redundant or duplicate State is a common source of bugs. In this chapter, you'll learn how to structure your State well, how to keep your State update logic maintainable, and how to share State between distant components.
-* [How to think about UI changes as state changes](/learn/reacting-to-input-with-state)
-* [How to structure state well](/learn/choosing-the-state-structure)
-* [How to "lift state up" to share it between components](/learn/sharing-state-between-components)
-* [How to control whether the state gets preserved or reset](/learn/preserving-and-resetting-state)
-* [How to consolidate complex state logic in a function](/learn/extracting-state-logic-into-a-reducer)
+* [How to think about UI changes as State changes](/learn/reacting-to-input-with-state)
+* [How to structure State well](/learn/choosing-the-state-structure)
+* [How to "lift State up" to share it between components](/learn/sharing-state-between-components)
+* [How to control whether the State gets preserved or reset](/learn/preserving-and-resetting-state)
+* [How to consolidate complex State logic in a function](/learn/extracting-state-logic-into-a-reducer)
* [How to pass information without "prop drilling"](/learn/passing-data-deeply-with-context)
-* [How to scale state management as your app grows](/learn/scaling-up-with-reducer-and-context)
+* [How to scale State management as your app grows](/learn/scaling-up-with-reducer-and-context)
-## Reacting to input with state {/*reacting-to-input-with-state*/}
+## Reacting to input with State {/*reacting-to-input-with-state*/}
-With React, you won't modify the UI from code directly. For example, you won't write commands like "disable the button", "enable the button", "show the success message", etc. Instead, you will describe the UI you want to see for the different visual states of your component ("initial state", "typing state", "success state"), and then trigger the state changes in response to user input. This is similar to how designers think about UI.
+With React, you won't modify the UI from code directly. For example, you won't write commands like "disable the button", "enable the button", "show the success message", etc. Instead, you will describe the UI you want to see for the different visual states of your component ("initial state", "typing state", "success state"), and then trigger the State changes in response to user input. This is similar to how designers think about UI.
-Here is a quiz form built using React. Note how it uses the `status` state variable to determine whether to enable or disable the submit button, and whether to show the success message instead.
+Here is a quiz form built using React. Note how it uses the `status` State variable to determine whether to enable or disable the submit button, and whether to show the success message instead.
@@ -108,15 +108,15 @@ function submitForm(answer) {
-Read **[Reacting to Input with State](/learn/reacting-to-input-with-state)** to learn how to approach interactions with a state-driven mindset.
+Read **[Reacting to Input with State](/learn/reacting-to-input-with-state)** to learn how to approach interactions with a State-driven mindset.
-## Choosing the state structure {/*choosing-the-state-structure*/}
+## Choosing the State structure {/*choosing-the-state-structure*/}
-Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. The most important principle is that state shouldn't contain redundant or duplicated information. If there's unnecessary state, it's easy to forget to update it, and introduce bugs!
+Structuring State well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. The most important principle is that State shouldn't contain redundant or duplicated information. If there's unnecessary State, it's easy to forget to update it, and introduce bugs!
-For example, this form has a **redundant** `fullName` state variable:
+For example, this form has a **redundant** `fullName` State variable:
@@ -225,15 +225,15 @@ This might seem like a small change, but many bugs in React apps are fixed this
-Read **[Choosing the State Structure](/learn/choosing-the-state-structure)** to learn how to design the state shape to avoid bugs.
+Read **[Choosing the State Structure](/learn/choosing-the-state-structure)** to learn how to design the State shape to avoid bugs.
-## Sharing state between components {/*sharing-state-between-components*/}
+## Sharing State between components {/*sharing-state-between-components*/}
-Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as "lifting state up", and it's one of the most common things you will do writing React code.
+Sometimes, you want the State of two components to always change together. To do it, remove State from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as "lifting State up", and it's one of the most common things you will do writing React code.
-In this example, only one panel should be active at a time. To achieve this, instead of keeping the active state inside each individual panel, the parent component holds the state and specifies the props for its children.
+In this example, only one panel should be active at a time. To achieve this, instead of keeping the active State inside each individual panel, the parent component holds the State and specifies the props for its children.
@@ -296,11 +296,11 @@ h3, p { margin: 5px 0px; }
-Read **[Sharing State Between Components](/learn/sharing-state-between-components)** to learn how to lift state up and keep components in sync.
+Read **[Sharing State Between Components](/learn/sharing-state-between-components)** to learn how to lift State up and keep components in sync.
-## Preserving and resetting state {/*preserving-and-resetting-state*/}
+## Preserving and resetting State {/*preserving-and-resetting-state*/}
When you re-render a component, React needs to decide which parts of the tree to keep (and update), and which parts to discard or re-create from scratch. In most cases, React's automatic behavior works well enough. By default, React preserves the parts of the tree that "match up" with the previously rendered component tree.
@@ -496,13 +496,13 @@ textarea {
-Read **[Preserving and Resetting State](/learn/preserving-and-resetting-state)** to learn the lifetime of state and how to control it.
+Read **[Preserving and Resetting State](/learn/preserving-and-resetting-state)** to learn the lifetime of State and how to control it.
-## Extracting state logic into a reducer {/*extracting-state-logic-into-a-reducer*/}
+## Extracting State logic into a reducer {/*extracting-state-logic-into-a-reducer*/}
-Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called "reducer". Your event handlers become concise because they only specify the user "actions". At the bottom of the file, the reducer function specifies how the state should update in response to each action!
+Components with many State updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the State update logic outside your component in a single function, called "reducer". Your event handlers become concise because they only specify the user "actions". At the bottom of the file, the reducer function specifies how the State should update in response to each action!
@@ -801,9 +801,9 @@ Read **[Passing Data Deeply with Context](/learn/passing-data-deeply-with-contex
## 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.
@@ -1006,7 +1006,7 @@ ul, li { margin: 0; padding: 0; }
-Read **[Scaling Up with Reducer and Context](/learn/scaling-up-with-reducer-and-context)** to learn how state management scales in a growing app.
+Read **[Scaling Up with Reducer and Context](/learn/scaling-up-with-reducer-and-context)** to learn how State management scales in a growing app.
diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md
index bc9a3eac472..f8a725a7655 100644
--- a/src/content/learn/manipulating-the-dom-with-refs.md
+++ b/src/content/learn/manipulating-the-dom-with-refs.md
@@ -80,7 +80,7 @@ To implement this:
3. In the `handleClick` function, read the input DOM node from `inputRef.current` and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it with `inputRef.current.focus()`.
4. Pass the `handleClick` event handler to `
-Notice how the moment you stop rendering the second counter, its state disappears completely. That's because when React removes a component, it destroys its state.
+Notice how the moment you stop rendering the second counter, its State disappears completely. That's because when React removes a component, it destroys its state.
@@ -476,13 +476,13 @@ label {
-You might expect the state to reset when you tick checkbox, but it doesn't! This is because **both of these `` tags are rendered at the same position.** React doesn't know where you place the conditions in your function. All it "sees" is the tree you return.
+You might expect the State to reset when you tick checkbox, but it doesn't! This is because **both of these `` tags are rendered at the same position.** React doesn't know where you place the conditions in your function. All it "sees" is the tree you return.
In both cases, the `App` component returns a `
` with `` as a first child. To React, these two counters have the same "address": the first child of the first child of the root. This is how React matches them up between the previous and next renders, regardless of how you structure your logic.
-## Different components at the same position reset state {/*different-components-at-the-same-position-reset-state*/}
+## Different components at the same position reset State {/*different-components-at-the-same-position-reset-state*/}
In this example, ticking the checkbox will replace `` with a `
`:
@@ -583,7 +583,7 @@ When switching back, the `p` is deleted and the `Counter` is added
-Also, **when you render a different component in the same position, it resets the state of its entire subtree.** To see how this works, increment the counter and then tick the checkbox:
+Also, **when you render a different component in the same position, it resets the State of its entire subtree.** To see how this works, increment the counter and then tick the checkbox:
@@ -1237,10 +1237,10 @@ No matter which strategy you pick, a chat _with Alice_ is conceptually distinct
-- React keeps state for as long as the same component is rendered at the same position.
+- React keeps State for as long as the same component is rendered at the same position.
- State is not kept in JSX tags. It's associated with the tree position in which you put that JSX.
-- You can force a subtree to reset its state by giving it a different key.
-- Don't nest component definitions, or you'll reset state by accident.
+- You can force a subtree to reset its State by giving it a different key.
+- Don't nest component definitions, or you'll reset State by accident.
@@ -1299,7 +1299,7 @@ textarea { display: block; margin: 10px 0; }
-The problem is that `Form` is rendered in different positions. In the `if` branch, it is the second child of the `
`, but in the `else` branch, it is the first child. Therefore, the component type in each position changes. The first position changes between holding a `p` and a `Form`, while the second position changes between holding a `Form` and a `button`. React resets the state every time the component type changes.
+The problem is that `Form` is rendered in different positions. In the `if` branch, it is the second child of the `
`, but in the `else` branch, it is the first child. Therefore, the component type in each position changes. The first position changes between holding a `p` and a `Form`, while the second position changes between holding a `Form` and a `button`. React resets the State every time the component type changes.
The easiest solution is to unify the branches so that `Form` always renders in the same position:
@@ -1471,7 +1471,7 @@ label { display: block; margin: 10px 0; }
-Give a `key` to both `` components in both `if` and `else` branches. This tells React how to "match up" the correct state for either `` even if their order within the parent changes:
+Give a `key` to both `` components in both `if` and `else` branches. This tells React how to "match up" the correct State for either `` even if their order within the parent changes:
@@ -1537,7 +1537,7 @@ label { display: block; margin: 10px 0; }
This is an editable contact list. You can edit the selected contact's details and then either press "Save" to update it, or "Reset" to undo your changes.
-When you select a different contact (for example, Alice), the state updates but the form keeps showing the previous contact's details. Fix it so that the form gets reset when the selected contact changes.
+When you select a different contact (for example, Alice), the State updates but the form keeps showing the previous contact's details. Fix it so that the form gets reset when the selected contact changes.
@@ -1986,11 +1986,11 @@ img { width: 150px; height: 150px; }
-#### Fix misplaced state in the list {/*fix-misplaced-state-in-the-list*/}
+#### Fix misplaced State in the list {/*fix-misplaced-state-in-the-list*/}
-In this list, each `Contact` has state that determines whether "Show email" has been pressed for it. Press "Show email" for Alice, and then tick the "Show in reverse order" checkbox. You will notice that it's _Taylor's_ email that is expanded now, but Alice's--which has moved to the bottom--appears collapsed.
+In this list, each `Contact` has State that determines whether "Show email" has been pressed for it. Press "Show email" for Alice, and then tick the "Show in reverse order" checkbox. You will notice that it's _Taylor's_ email that is expanded now, but Alice's--which has moved to the bottom--appears collapsed.
-Fix it so that the expanded state is associated with each contact, regardless of the chosen ordering.
+Fix it so that the expanded State is associated with each contact, regardless of the chosen ordering.
@@ -2087,7 +2087,7 @@ The problem is that this example was using index as a `key`:
```
-However, you want the state to be associated with _each particular contact_.
+However, you want the State to be associated with _each particular contact_.
Using the contact ID as a `key` instead fixes the issue:
diff --git a/src/content/learn/queueing-a-series-of-state-updates.md b/src/content/learn/queueing-a-series-of-state-updates.md
index 41de6529a6d..5ac1f98c2c3 100644
--- a/src/content/learn/queueing-a-series-of-state-updates.md
+++ b/src/content/learn/queueing-a-series-of-state-updates.md
@@ -4,18 +4,18 @@ title: Queueing a Series of State Updates
-Setting a state variable will queue another render. But sometimes you might want to perform multiple operations on the value before queueing the next render. To do this, it helps to understand how React batches state updates.
+Setting a State variable will queue another render. But sometimes you might want to perform multiple operations on the value before queueing the next render. To do this, it helps to understand how React batches State updates.
-* What "batching" is and how React uses it to process multiple state updates
-* How to apply several updates to the same state variable in a row
+* What "batching" is and how React uses it to process multiple State updates
+* How to apply several updates to the same State variable in a row
-## React batches state updates {/*react-batches-state-updates*/}
+## React batches State updates {/*react-batches-state-updates*/}
You might expect that clicking the "+3" button will increment the counter three times because it calls `setNumber(number + 1)` three times:
@@ -55,19 +55,19 @@ setNumber(0 + 1);
setNumber(0 + 1);
```
-But there is one other factor at play here. **React waits until *all* code in the event handlers has run before processing your state updates.** This is why the re-render only happens *after* all these `setNumber()` calls.
+But there is one other factor at play here. **React waits until *all* code in the event handlers has run before processing your State updates.** This is why the re-render only happens *after* all these `setNumber()` calls.
This might remind you of a waiter taking an order at the restaurant. A waiter doesn't run to the kitchen at the mention of your first dish! Instead, they let you finish your order, let you make changes to it, and even take orders from other people at the table.
-This lets you update multiple state variables--even from multiple components--without triggering too many [re-renders.](/learn/render-and-commit#re-renders-when-state-updates) But this also means that the UI won't be updated until _after_ your event handler, and any code in it, completes. This behavior, also known as **batching,** makes your React app run much faster. It also avoids dealing with confusing "half-finished" renders where only some of the variables have been updated.
+This lets you update multiple State variables--even from multiple components--without triggering too many [re-renders.](/learn/render-and-commit#re-renders-when-state-updates) But this also means that the UI won't be updated until _after_ your event handler, and any code in it, completes. This behavior, also known as **batching,** makes your React app run much faster. It also avoids dealing with confusing "half-finished" renders where only some of the variables have been updated.
**React does not batch across *multiple* intentional events like clicks**--each click is handled separately. Rest assured that React only does batching when it's generally safe to do. This ensures that, for example, if the first button click disables a form, the second click would not submit it again.
-## Updating the same state multiple times before the next render {/*updating-the-same-state-multiple-times-before-the-next-render*/}
+## Updating the same State multiple times before the next render {/*updating-the-same-state-multiple-times-before-the-next-render*/}
-It is an uncommon use case, but if you would like to update the same state variable multiple times before the next render, instead of passing the *next state value* like `setNumber(number + 1)`, you can pass a *function* that calculates the next state based on the previous one in the queue, like `setNumber(n => n + 1)`. It is a way to tell React to "do something with the state value" instead of just replacing it.
+It is an uncommon use case, but if you would like to update the same State variable multiple times before the next render, instead of passing the *next State value* like `setNumber(number + 1)`, you can pass a *function* that calculates the next State based on the previous one in the queue, like `setNumber(n => n + 1)`. It is a way to tell React to "do something with the State value" instead of just replacing it.
Try incrementing the counter now:
@@ -99,10 +99,10 @@ h1 { display: inline-block; margin: 10px; width: 30px; text-align: center; }
-Here, `n => n + 1` is called an **updater function.** When you pass it to a state setter:
+Here, `n => n + 1` is called an **updater function.** When you pass it to a State setter:
1. React queues this function to be processed after all the other code in the event handler has run.
-2. During the next render, React goes through the queue and gives you the final updated state.
+2. During the next render, React goes through the queue and gives you the final updated State.
```js
setNumber(n => n + 1);
@@ -116,7 +116,7 @@ Here's how React works through these lines of code while executing the event han
1. `setNumber(n => n + 1)`: `n => n + 1` is a function. React adds it to a queue.
1. `setNumber(n => n + 1)`: `n => n + 1` is a function. React adds it to a queue.
-When you call `useState` during the next render, React goes through the queue. The previous `number` state was `0`, so that's what React passes to the first updater function as the `n` argument. Then React takes the return value of your previous updater function and passes it to the next updater as `n`, and so on:
+When you call `useState` during the next render, React goes through the queue. The previous `number` State was `0`, so that's what React passes to the first updater function as the `n` argument. Then React takes the return value of your previous updater function and passes it to the next updater as `n`, and so on:
| queued update | `n` | returns |
|--------------|---------|-----|
@@ -127,7 +127,7 @@ When you call `useState` during the next render, React goes through the queue. T
React stores `3` as the final result and returns it from `useState`.
This is why clicking "+3" in the above example correctly increments the value by 3.
-### What happens if you update state after replacing it {/*what-happens-if-you-update-state-after-replacing-it*/}
+### What happens if you update State after replacing it {/*what-happens-if-you-update-state-after-replacing-it*/}
What about this event handler? What do you think `number` will be in the next render?
@@ -170,7 +170,7 @@ Here's what this event handler tells React to do:
1. `setNumber(number + 5)`: `number` is `0`, so `setNumber(0 + 5)`. React adds *"replace with `5`"* to its queue.
2. `setNumber(n => n + 1)`: `n => n + 1` is an updater function. React adds *that function* to its queue.
-During the next render, React goes through the state queue:
+During the next render, React goes through the State queue:
| queued update | `n` | returns |
|--------------|---------|-----|
@@ -185,7 +185,7 @@ You may have noticed that `setState(5)` actually works like `setState(n => 5)`,
-### What happens if you replace state after updating it {/*what-happens-if-you-replace-state-after-updating-it*/}
+### What happens if you replace State after updating it {/*what-happens-if-you-replace-state-after-updating-it*/}
Let's try one more example. What do you think `number` will be in the next render?
@@ -231,7 +231,7 @@ Here's how React works through these lines of code while executing this event ha
2. `setNumber(n => n + 1)`: `n => n + 1` is an updater function. React adds *that function* to its queue.
3. `setNumber(42)`: React adds *"replace with `42`"* to its queue.
-During the next render, React goes through the state queue:
+During the next render, React goes through the State queue:
| queued update | `n` | returns |
|--------------|---------|-----|
@@ -241,16 +241,16 @@ During the next render, React goes through the state queue:
Then React stores `42` as the final result and returns it from `useState`.
-To summarize, here's how you can think of what you're passing to the `setNumber` state setter:
+To summarize, here's how you can think of what you're passing to the `setNumber` State setter:
* **An updater function** (e.g. `n => n + 1`) gets added to the queue.
* **Any other value** (e.g. number `5`) adds "replace with `5`" to the queue, ignoring what's already queued.
-After the event handler completes, React will trigger a re-render. During the re-render, React will process the queue. Updater functions run during rendering, so **updater functions must be [pure](/learn/keeping-components-pure)** and only *return* the result. Don't try to set state from inside of them or run other side effects. In Strict Mode, React will run each updater function twice (but discard the second result) to help you find mistakes.
+After the event handler completes, React will trigger a re-render. During the re-render, React will process the queue. Updater functions run during rendering, so **updater functions must be [pure](/learn/keeping-components-pure)** and only *return* the result. Don't try to set State from inside of them or run other side effects. In Strict Mode, React will run each updater function twice (but discard the second result) to help you find mistakes.
### Naming conventions {/*naming-conventions*/}
-It's common to name the updater function argument by the first letters of the corresponding state variable:
+It's common to name the updater function argument by the first letters of the corresponding State variable:
```js
setEnabled(e => !e);
@@ -258,13 +258,13 @@ setLastName(ln => ln.reverse());
setFriendCount(fc => fc * 2);
```
-If you prefer more verbose code, another common convention is to repeat the full state variable name, like `setEnabled(enabled => !enabled)`, or to use a prefix like `setEnabled(prevEnabled => !prevEnabled)`.
+If you prefer more verbose code, another common convention is to repeat the full State variable name, like `setEnabled(enabled => !enabled)`, or to use a prefix like `setEnabled(prevEnabled => !prevEnabled)`.
-* Setting state does not change the variable in the existing render, but it requests a new render.
-* React processes state updates after event handlers have finished running. This is called batching.
-* To update some state multiple times in one event, you can use `setNumber(n => n + 1)` updater function.
+* Setting State does not change the variable in the existing render, but it requests a new render.
+* React processes State updates after event handlers have finished running. This is called batching.
+* To update some State multiple times in one event, you can use `setNumber(n => n + 1)` updater function.
@@ -364,19 +364,19 @@ function delay(ms) {
-This ensures that when you increment or decrement a counter, you do it in relation to its *latest* state rather than what the state was at the time of the click.
+This ensures that when you increment or decrement a counter, you do it in relation to its *latest* State rather than what the State was at the time of the click.
-#### Implement the state queue yourself {/*implement-the-state-queue-yourself*/}
+#### Implement the State queue yourself {/*implement-the-state-queue-yourself*/}
In this challenge, you will reimplement a tiny part of React from scratch! It's not as hard as it sounds.
Scroll through the sandbox preview. Notice that it shows **four test cases.** They correspond to the examples you've seen earlier on this page. Your task is to implement the `getFinalState` function so that it returns the correct result for each of those cases. If you implement it correctly, all four tests should pass.
-You will receive two arguments: `baseState` is the initial state (like `0`), and the `queue` is an array which contains a mix of numbers (like `5`) and updater functions (like `n => n + 1`) in the order they were added.
+You will receive two arguments: `baseState` is the initial State (like `0`), and the `queue` is an array which contains a mix of numbers (like `5`) and updater functions (like `n => n + 1`) in the order they were added.
-Your task is to return the final state, just like the tables on this page show!
+Your task is to return the final State, just like the tables on this page show!
@@ -495,7 +495,7 @@ function TestCase({
-This is the exact algorithm described on this page that React uses to calculate the final state:
+This is the exact algorithm described on this page that React uses to calculate the final State:
@@ -600,4 +600,4 @@ Now you know how this part of React works!
-
\ No newline at end of file
+
diff --git a/src/content/learn/reacting-to-input-with-state.md b/src/content/learn/reacting-to-input-with-state.md
index da559dc0fac..ed0688aa528 100644
--- a/src/content/learn/reacting-to-input-with-state.md
+++ b/src/content/learn/reacting-to-input-with-state.md
@@ -4,7 +4,7 @@ title: Reacting to Input with State
-React provides a declarative way to manipulate the UI. Instead of manipulating individual pieces of the UI directly, you describe the different states that your component can be in, and switch between them in response to the user input. This is similar to how designers think about the UI.
+React provides a declarative way to manipulate the UI. Instead of manipulating individual pieces of the UI directly, you describe the different States that your component can be in, and switch between them in response to the user input. This is similar to how designers think about the UI.
@@ -311,9 +311,9 @@ Pages like this are often called "living styleguides" or "storybooks".
-### Step 2: Determine what triggers those state changes {/*step-2-determine-what-triggers-those-state-changes*/}
+### Step 2: Determine what triggers those State changes {/*step-2-determine-what-triggers-those-state-changes*/}
-You can trigger state updates in response to two kinds of inputs:
+You can trigger State updates in response to two kinds of inputs:
* **Human inputs,** like clicking a button, typing in a field, navigating a link.
* **Computer inputs,** like a network response arriving, a timeout completing, an image loading.
@@ -323,7 +323,7 @@ You can trigger state updates in response to two kinds of inputs:
-In both cases, **you must set [state variables](/learn/state-a-components-memory#anatomy-of-usestate) to update the UI.** For the form you're developing, you will need to change state in response to a few different inputs:
+In both cases, **you must set [state variables](/learn/state-a-components-memory#anatomy-of-usestate) to update the UI.** For the form you're developing, you will need to change State in response to a few different inputs:
* **Changing the text input** (human) should switch it from the *Empty* state to the *Typing* state or back, depending on whether the text box is empty or not.
* **Clicking the Submit button** (human) should switch it to the *Submitting* state.
@@ -336,7 +336,7 @@ Notice that human inputs often require [event handlers](/learn/responding-to-eve
-To help visualize this flow, try drawing each state on paper as a labeled circle, and each change between two states as an arrow. You can sketch out many flows this way and sort out bugs long before implementation.
+To help visualize this flow, try drawing each State on paper as a labeled circle, and each change between two States as an arrow. You can sketch out many flows this way and sort out bugs long before implementation.
@@ -840,7 +840,7 @@ label { display: block; margin-bottom: 20px; }
-You will need two state variables to hold the input values: `firstName` and `lastName`. You're also going to need an `isEditing` state variable that holds whether to display the inputs or not. You should _not_ need a `fullName` variable because the full name can always be calculated from the `firstName` and the `lastName`.
+You will need two State variables to hold the input values: `firstName` and `lastName`. You're also going to need an `isEditing` State variable that holds whether to display the inputs or not. You should _not_ need a `fullName` variable because the full name can always be calculated from the `firstName` and the `lastName`.
Finally, you should use [conditional rendering](/learn/conditional-rendering) to show or hide the inputs depending on `isEditing`.
@@ -1003,7 +1003,7 @@ label { display: block; margin-bottom: 20px; }
-Imagine React didn't exist. Can you refactor this code in a way that makes the logic less fragile and more similar to the React version? What would it look like if the state was explicit, like in React?
+Imagine React didn't exist. Can you refactor this code in a way that makes the logic less fragile and more similar to the React version? What would it look like if the State was explicit, like in React?
If you're struggling to think where to start, the stub below already has most of the structure in place. If you start here, fill in the missing logic in the `updateDOM` function. (Refer to the original code where needed.)
@@ -1229,7 +1229,7 @@ label { display: block; margin-bottom: 20px; }
-The `updateDOM` function you wrote shows what React does under the hood when you set the state. (However, React also avoids touching the DOM for properties that have not changed since the last time they were set.)
+The `updateDOM` function you wrote shows what React does under the hood when you set the State. (However, React also avoids touching the DOM for properties that have not changed since the last time they were set.)
diff --git a/src/content/learn/referencing-values-with-refs.md b/src/content/learn/referencing-values-with-refs.md
index 4faf18786f6..c6bfaf8e370 100644
--- a/src/content/learn/referencing-values-with-refs.md
+++ b/src/content/learn/referencing-values-with-refs.md
@@ -12,7 +12,7 @@ When you want a component to "remember" some information, but you don't want tha
- How to add a ref to your component
- How to update a ref's value
-- How refs are different from state
+- How refs are different from State
- How to use refs safely
@@ -68,13 +68,13 @@ export default function Counter() {
-The ref points to a number, but, like [state](/learn/state-a-components-memory), you could point to anything: a string, an object, or even a function. Unlike state, ref is a plain JavaScript object with the `current` property that you can read and modify.
+The ref points to a number, but, like [state](/learn/state-a-components-memory), you could point to anything: a string, an object, or even a function. Unlike State, ref is a plain JavaScript object with the `current` property that you can read and modify.
-Note that **the component doesn't re-render with every increment.** Like state, refs are retained by React between re-renders. However, setting state re-renders a component. Changing a ref does not!
+Note that **the component doesn't re-render with every increment.** Like State, refs are retained by React between re-renders. However, setting State re-renders a component. Changing a ref does not!
## Example: building a stopwatch {/*example-building-a-stopwatch*/}
-You can combine refs and state in a single component. For example, let's make a stopwatch that the user can start or stop by pressing a button. In order to display how much time has passed since the user pressed "Start", you will need to keep track of when the Start button was pressed and what the current time is. **This information is used for rendering, so you'll keep it in state:**
+You can combine refs and State in a single component. For example, let's make a stopwatch that the user can start or stop by pressing a button. In order to display how much time has passed since the user pressed "Start", you will need to keep track of when the Start button was pressed and what the current time is. **This information is used for rendering, so you'll keep it in state:**
```js
const [startTime, setStartTime] = useState(null);
@@ -121,7 +121,7 @@ export default function Stopwatch() {
-When the "Stop" button is pressed, you need to cancel the existing interval so that it stops updating the `now` state variable. You can do this by calling [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval), but you need to give it the interval ID that was previously returned by the `setInterval` call when the user pressed Start. You need to keep the interval ID somewhere. **Since the interval ID is not used for rendering, you can keep it in a ref:**
+When the "Stop" button is pressed, you need to cancel the existing interval so that it stops updating the `now` State variable. You can do this by calling [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval), but you need to give it the interval ID that was previously returned by the `setInterval` call when the user pressed Start. You need to keep the interval ID somewhere. **Since the interval ID is not used for rendering, you can keep it in a ref:**
@@ -168,20 +168,20 @@ export default function Stopwatch() {
-When a piece of information is used for rendering, keep it in state. When a piece of information is only needed by event handlers and changing it doesn't require a re-render, using a ref may be more efficient.
+When a piece of information is used for rendering, keep it in State. When a piece of information is only needed by event handlers and changing it doesn't require a re-render, using a ref may be more efficient.
-## Differences between refs and state {/*differences-between-refs-and-state*/}
+## Differences between refs and State {/*differences-between-refs-and-state*/}
-Perhaps you're thinking refs seem less "strict" than state—you can mutate them instead of always having to use a state setting function, for instance. But in most cases, you'll want to use state. Refs are an "escape hatch" you won't need often. Here's how state and refs compare:
+Perhaps you're thinking refs seem less "strict" than State—you can mutate them instead of always having to use a State setting function, for instance. But in most cases, you'll want to use State. Refs are an "escape hatch" you won't need often. Here's how State and refs compare:
| refs | state |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
-| `useRef(initialValue)` returns `{ current: initialValue }` | `useState(initialValue)` returns the current value of a state variable and a state setter function ( `[value, setValue]`) |
+| `useRef(initialValue)` returns `{ current: initialValue }` | `useState(initialValue)` returns the current value of a State variable and a State setter function ( `[value, setValue]`) |
| Doesn't trigger re-render when you change it. | Triggers re-render when you change it. |
-| Mutable—you can modify and update `current`'s value outside of the rendering process. | "Immutable"—you must use the state setting function to modify state variables to queue a re-render. |
-| You shouldn't read (or write) the `current` value during rendering. | You can read state at any time. However, each render has its own [snapshot](/learn/state-as-a-snapshot) of state which does not change.
+| Mutable—you can modify and update `current`'s value outside of the rendering process. | "Immutable"—you must use the State setting function to modify State variables to queue a re-render. |
+| You shouldn't read (or write) the `current` value during rendering. | You can read State at any time. However, each render has its own [snapshot](/learn/state-as-a-snapshot) of State which does not change.
-Here is a counter button that's implemented with state:
+Here is a counter button that's implemented with State:
@@ -205,7 +205,7 @@ export default function Counter() {
-Because the `count` value is displayed, it makes sense to use a state value for it. When the counter's value is set with `setCount()`, React re-renders the component and the screen updates to reflect the new count.
+Because the `count` value is displayed, it makes sense to use a State value for it. When the counter's value is set with `setCount()`, React re-renders the component and the screen updates to reflect the new count.
If you tried to implement this with a ref, React would never re-render the component, so you'd never see the count change! See how clicking this button **does not update its text**:
@@ -232,7 +232,7 @@ export default function Counter() {
-This is why reading `ref.current` during render leads to unreliable code. If you need that, use state instead.
+This is why reading `ref.current` during render leads to unreliable code. If you need that, use State instead.
@@ -248,9 +248,9 @@ function useRef(initialValue) {
}
```
-During the first render, `useRef` returns `{ current: initialValue }`. This object is stored by React, so during the next render the same object will be returned. Note how the state setter is unused in this example. It is unnecessary because `useRef` always needs to return the same object!
+During the first render, `useRef` returns `{ current: initialValue }`. This object is stored by React, so during the next render the same object will be returned. Note how the State setter is unused in this example. It is unnecessary because `useRef` always needs to return the same object!
-React provides a built-in version of `useRef` because it is common enough in practice. But you can think of it as a regular state variable without a setter. If you're familiar with object-oriented programming, refs might remind you of instance fields--but instead of `this.something` you write `somethingRef.current`.
+React provides a built-in version of `useRef` because it is common enough in practice. But you can think of it as a regular State variable without a setter. If you're familiar with object-oriented programming, refs might remind you of instance fields--but instead of `this.something` you write `somethingRef.current`.
@@ -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;
@@ -291,8 +291,8 @@ You can point a ref to any value. However, the most common use case for a ref is
- Refs are an escape hatch to hold onto values that aren't used for rendering. You won't need them often.
- A ref is a plain JavaScript object with a single property called `current`, which you can read or set.
- You can ask React to give you a ref by calling the `useRef` Hook.
-- Like state, refs let you retain information between re-renders of a component.
-- Unlike state, setting the ref's `current` value does not trigger a re-render.
+- Like State, refs let you retain information between re-renders of a component.
+- Unlike State, setting the ref's `current` value does not trigger a re-render.
- Don't read or write `ref.current` during rendering. This makes your component hard to predict.
@@ -360,7 +360,7 @@ export default function Chat() {
-Whenever your component re-renders (such as when you set state), all local variables get initialized from scratch. This is why you can't save the timeout ID in a local variable like `timeoutID` and then expect another event handler to "see" it in the future. Instead, store it in a ref, which React will preserve between renders.
+Whenever your component re-renders (such as when you set State), all local variables get initialized from scratch. This is why you can't save the timeout ID in a local variable like `timeoutID` and then expect another event handler to "see" it in the future. Instead, store it in a ref, which React will preserve between renders.
@@ -438,7 +438,7 @@ export default function Toggle() {
-In this example, the current value of a ref is used to calculate the rendering output: `{isOnRef.current ? 'On' : 'Off'}`. This is a sign that this information should not be in a ref, and should have instead been put in state. To fix it, remove the ref and use state instead:
+In this example, the current value of a ref is used to calculate the rendering output: `{isOnRef.current ? 'On' : 'Off'}`. This is a sign that this information should not be in a ref, and should have instead been put in State. To fix it, remove the ref and use State instead:
@@ -577,11 +577,11 @@ button { display: block; margin: 10px; }
-#### Read the latest state {/*read-the-latest-state*/}
+#### Read the latest State {/*read-the-latest-state*/}
-In this example, after you press "Send", there is a small delay before the message is shown. Type "hello", press Send, and then quickly edit the input again. Despite your edits, the alert would still show "hello" (which was the value of state [at the time](/learn/state-as-a-snapshot#state-over-time) the button was clicked).
+In this example, after you press "Send", there is a small delay before the message is shown. Type "hello", press Send, and then quickly edit the input again. Despite your edits, the alert would still show "hello" (which was the value of State [at the time](/learn/state-as-a-snapshot#state-over-time) the button was clicked).
-Usually, this behavior is what you want in an app. However, there may be occasional cases where you want some asynchronous code to read the *latest* version of some state. Can you think of a way to make the alert show the *current* input text rather than what it was at the time of the click?
+Usually, this behavior is what you want in an app. However, there may be occasional cases where you want some asynchronous code to read the *latest* version of some State. Can you think of a way to make the alert show the *current* input text rather than what it was at the time of the click?
@@ -616,7 +616,7 @@ export default function Chat() {
-State works [like a snapshot](/learn/state-as-a-snapshot), so you can't read the latest state from an asynchronous operation like a timeout. However, you can keep the latest input text in a ref. A ref is mutable, so you can read the `current` property at any time. Since the current text is also used for rendering, in this example, you will need *both* a state variable (for rendering), *and* a ref (to read it in the timeout). You will need to update the current ref value manually.
+State works [like a snapshot](/learn/state-as-a-snapshot), so you can't read the latest State from an asynchronous operation like a timeout. However, you can keep the latest input text in a ref. A ref is mutable, so you can read the `current` property at any time. Since the current text is also used for rendering, in this example, you will need *both* a State variable (for rendering), *and* a ref (to read it in the timeout). You will need to update the current ref value manually.
diff --git a/src/content/learn/removing-effect-dependencies.md b/src/content/learn/removing-effect-dependencies.md
index 9a871c6c3f0..efa5c28c158 100644
--- a/src/content/learn/removing-effect-dependencies.md
+++ b/src/content/learn/removing-effect-dependencies.md
@@ -4,7 +4,7 @@ title: 'Removing Effect Dependencies'
-When you write an Effect, the linter will verify that you've included every reactive value (like props and state) that the Effect reads in the list of your Effect's dependencies. This ensures that your Effect remains synchronized with the latest props and state of your component. Unnecessary dependencies may cause your Effect to run too often, or even create an infinite loop. Follow this guide to review and remove unnecessary dependencies from your Effects.
+When you write an Effect, the linter will verify that you've included every reactive value (like props and State) that the Effect reads in the list of your Effect's dependencies. This ensures that your Effect remains synchronized with the latest props and State of your component. Unnecessary dependencies may cause your Effect to run too often, or even create an infinite loop. Follow this guide to review and remove unnecessary dependencies from your Effects.
@@ -263,7 +263,7 @@ button { margin-left: 10px; }
-This is why you could now specify an [empty (`[]`) dependency list.](/learn/lifecycle-of-reactive-effects#what-an-effect-with-empty-dependencies-means) Your Effect *really doesn't* depend on any reactive value anymore, so it *really doesn't* need to re-run when any of the component's props or state change.
+This is why you could now specify an [empty (`[]`) dependency list.](/learn/lifecycle-of-reactive-effects#what-an-effect-with-empty-dependencies-means) Your Effect *really doesn't* depend on any reactive value anymore, so it *really doesn't* need to re-run when any of the component's props or State change.
### To change the dependencies, change the code {/*to-change-the-dependencies-change-the-code*/}
@@ -372,7 +372,7 @@ To find the right solution, you'll need to answer a few questions about your Eff
The first thing you should think about is whether this code should be an Effect at all.
-Imagine a form. On submit, you set the `submitted` state variable to `true`. You need to send a POST request and show a notification. You've put this logic inside an Effect that "reacts" to `submitted` being `true`:
+Imagine a form. On submit, you set the `submitted` State variable to `true`. You need to send a POST request and show a notification. You've put this logic inside an Effect that "reacts" to `submitted` being `true`:
```js {6-8}
function Form() {
@@ -465,7 +465,7 @@ function ShippingForm({ country }) {
// ...
```
-This is a good example of [fetching data in an Effect.](/learn/you-might-not-need-an-effect#fetching-data) You are synchronizing the `cities` state with the network according to the `country` prop. You can't do this in an event handler because you need to fetch as soon as `ShippingForm` is displayed and whenever the `country` changes (no matter which interaction causes it).
+This is a good example of [fetching data in an Effect.](/learn/you-might-not-need-an-effect#fetching-data) You are synchronizing the `cities` State with the network according to the `country` prop. You can't do this in an event handler because you need to fetch as soon as `ShippingForm` is displayed and whenever the `country` changes (no matter which interaction causes it).
Now let's say you're adding a second select box for city areas, which should fetch the `areas` for the currently selected `city`. You might start by adding a second `fetch` call for the list of areas inside the same Effect:
@@ -502,12 +502,12 @@ function ShippingForm({ country }) {
// ...
```
-However, since the Effect now uses the `city` state variable, you've had to add `city` to the list of dependencies. That, in turn, introduced a problem: when the user selects a different city, the Effect will re-run and call `fetchCities(country)`. As a result, you will be unnecessarily refetching the list of cities many times.
+However, since the Effect now uses the `city` State variable, you've had to add `city` to the list of dependencies. That, in turn, introduced a problem: when the user selects a different city, the Effect will re-run and call `fetchCities(country)`. As a result, you will be unnecessarily refetching the list of cities many times.
**The problem with this code is that you're synchronizing two different unrelated things:**
-1. You want to synchronize the `cities` state to the network based on the `country` prop.
-1. You want to synchronize the `areas` state to the network based on the `city` state.
+1. You want to synchronize the `cities` State to the network based on the `country` prop.
+1. You want to synchronize the `areas` State to the network based on the `city` State.
Split the logic into two Effects, each of which reacts to the prop that it needs to synchronize with:
@@ -553,9 +553,9 @@ Now the first Effect only re-runs if the `country` changes, while the second Eff
The final code is longer than the original, but splitting these Effects is still correct. [Each Effect should represent an independent synchronization process.](/learn/lifecycle-of-reactive-effects#each-effect-represents-a-separate-synchronization-process) In this example, deleting one Effect doesn't break the other Effect's logic. This means they *synchronize different things,* and it's good to split them up. If you're concerned about duplication, you can improve this code by [extracting repetitive logic into a custom Hook.](/learn/reusing-logic-with-custom-hooks#when-to-use-custom-hooks)
-### Are you reading some state to calculate the next state? {/*are-you-reading-some-state-to-calculate-the-next-state*/}
+### Are you reading some State to calculate the next State? {/*are-you-reading-some-state-to-calculate-the-next-state*/}
-This Effect updates the `messages` state variable with a newly created array every time a new message arrives:
+This Effect updates the `messages` State variable with a newly created array every time a new message arrives:
```js {2,6-8}
function ChatRoom({ roomId }) {
@@ -867,7 +867,7 @@ button { margin-left: 10px; }
-In the sandbox above, the input only updates the `message` state variable. From the user's perspective, this should not affect the chat connection. However, every time you update the `message`, your component re-renders. When your component re-renders, the code inside of it runs again from scratch.
+In the sandbox above, the input only updates the `message` State variable. From the user's perspective, this should not affect the chat connection. However, every time you update the `message`, your component re-renders. When your component re-renders, the code inside of it runs again from scratch.
A new `options` object is created from scratch on every re-render of the `ChatRoom` component. React sees that the `options` object is a *different object* from the `options` object created during the last render. This is why it re-synchronizes your Effect (which depends on `options`), and the chat re-connects as you type.
@@ -890,7 +890,7 @@ This is why, whenever possible, you should try to avoid objects and functions as
#### Move static objects and functions outside your component {/*move-static-objects-and-functions-outside-your-component*/}
-If the object does not depend on any props and state, you can move that object outside your component:
+If the object does not depend on any props and State, you can move that object outside your component:
```js {1-4,13}
const options = {
@@ -1179,7 +1179,7 @@ This Effect sets up an interval that ticks every second. You've noticed somethin
-It seems like this Effect's code depends on `count`. Is there some way to not need this dependency? There should be a way to update the `count` state based on its previous value without adding a dependency on that value.
+It seems like this Effect's code depends on `count`. Is there some way to not need this dependency? There should be a way to update the `count` State based on its previous value without adding a dependency on that value.
@@ -1211,7 +1211,7 @@ export default function Timer() {
-You want to update the `count` state to be `count + 1` from inside the Effect. However, this makes your Effect depend on `count`, which changes with every tick, and that's why your interval gets re-created on every tick.
+You want to update the `count` State to be `count + 1` from inside the Effect. However, this makes your Effect depend on `count`, which changes with every tick, and that's why your interval gets re-created on every tick.
To solve this, use the [updater function](/reference/react/useState#updating-state-based-on-the-previous-state) and write `setCount(c => c + 1)` instead of `setCount(count + 1)`:
@@ -1249,7 +1249,7 @@ Instead of reading `count` inside the Effect, you pass a `c => c + 1` instructio
In this example, when you press "Show", a welcome message fades in. The animation takes a second. When you press "Remove", the welcome message immediately disappears. The logic for the fade-in animation is implemented in the `animation.js` file as plain JavaScript [animation loop.](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) You don't need to change that logic. You can treat it as a third-party library. Your Effect creates an instance of `FadeInAnimation` for the DOM node, and then calls `start(duration)` or `stop()` to control the animation. The `duration` is controlled by a slider. Adjust the slider and see how the animation changes.
-This code already works, but there is something you want to change. Currently, when you move the slider that controls the `duration` state variable, it retriggers the animation. Change the behavior so that the Effect does not "react" to the `duration` variable. When you press "Show", the Effect should use the current `duration` on the slider. However, moving the slider itself should not by itself retrigger the animation.
+This code already works, but there is something you want to change. Currently, when you move the slider that controls the `duration` State variable, it retriggers the animation. Change the behavior so that the Effect does not "react" to the `duration` variable. When you press "Show", the Effect should use the current `duration` on the slider. However, moving the slider itself should not by itself retrigger the animation.
@@ -1816,7 +1816,7 @@ You're passing down two functions: `onMessage` and `createConnection`. Both of t
One of these functions is an event handler. Do you know some way to call an event handler an Effect without "reacting" to the new values of the event handler function? That would come in handy!
-Another of these functions only exists to pass some state to an imported API method. Is this function really necessary? What is the essential information that's being passed down? You might need to move some imports from `App.js` to `ChatRoom.js`.
+Another of these functions only exists to pass some State to an imported API method. Is this function really necessary? What is the essential information that's being passed down? You might need to move some imports from `App.js` to `ChatRoom.js`.
diff --git a/src/content/learn/render-and-commit.md b/src/content/learn/render-and-commit.md
index 3f05935992c..622ef124a04 100644
--- a/src/content/learn/render-and-commit.md
+++ b/src/content/learn/render-and-commit.md
@@ -34,7 +34,7 @@ Imagine that your components are cooks in the kitchen, assembling tasty dishes f
There are two reasons for a component to render:
1. It's the component's **initial render.**
-2. The component's (or one of its ancestors') **state has been updated.**
+2. The component's (or one of its ancestors') **State has been updated.**
### Initial render {/*initial-render*/}
@@ -65,9 +65,9 @@ export default function Image() {
Try commenting out the `root.render()` call and see the component disappear!
-### Re-renders when state updates {/*re-renders-when-state-updates*/}
+### Re-renders when State updates {/*re-renders-when-state-updates*/}
-Once the component has been initially rendered, you can trigger further renders by updating its state with the [`set` function.](/reference/react/useState#setstate) Updating your component's state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.)
+Once the component has been initially rendered, you can trigger further renders by updating its State with the [`set` function.](/reference/react/useState#setstate) Updating your component's state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.)
@@ -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 13a556c7b15..3307261bfe2 100644
--- a/src/content/learn/reusing-logic-with-custom-hooks.md
+++ b/src/content/learn/reusing-logic-with-custom-hooks.md
@@ -21,8 +21,8 @@ React comes with several built-in Hooks like `useState`, `useContext`, and `useE
Imagine you're developing an app that heavily relies on the network (as most apps do). You want to warn the user if their network connection has accidentally gone off while they were using your app. How would you go about it? It seems like you'll need two things in your component:
-1. A piece of state that tracks whether the network is online.
-2. An Effect that subscribes to the global [`online`](https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event) and [`offline`](https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event) events, and updates that state.
+1. A piece of State that tracks whether the network is online.
+2. An Effect that subscribes to the global [`online`](https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event) and [`offline`](https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event) events, and updates that State.
This will keep your component [synchronized](/learn/synchronizing-with-effects) with the network status. You might start with something like this:
@@ -58,7 +58,7 @@ Try turning your network on and off, and notice how this `StatusBar` updates in
Now imagine you *also* want to use the same logic in a different component. You want to implement a Save button that will become disabled and show "Reconnecting..." instead of "Save" while the network is off.
-To start, you can copy and paste the `isOnline` state and the Effect into `SaveButton`:
+To start, you can copy and paste the `isOnline` State and the Effect into `SaveButton`:
@@ -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!
@@ -289,9 +289,9 @@ Then components won't be able to call it conditionally. This will become importa
-### Custom Hooks let you share stateful logic, not state itself {/*custom-hooks-let-you-share-stateful-logic-not-state-itself*/}
+### Custom Hooks let you share stateful logic, not State itself {/*custom-hooks-let-you-share-stateful-logic-not-state-itself*/}
-In the earlier example, when you turned the network on and off, both components updated together. However, it's wrong to think that a single `isOnline` state variable is shared between them. Look at this code:
+In the earlier example, when you turned the network on and off, both components updated together. However, it's wrong to think that a single `isOnline` State variable is shared between them. Look at this code:
```js {2,7}
function StatusBar() {
@@ -325,7 +325,7 @@ function SaveButton() {
}
```
-These are two completely independent state variables and Effects! They happened to have the same value at the same time because you synchronized them with the same external value (whether the network is on).
+These are two completely independent State variables and Effects! They happened to have the same value at the same time because you synchronized them with the same external value (whether the network is on).
To better illustrate this, we'll need a different example. Consider this `Form` component:
@@ -428,7 +428,7 @@ input { margin-left: 10px; }
-Notice that it only declares *one* state variable called `value`.
+Notice that it only declares *one* State variable called `value`.
However, the `Form` component calls `useFormInput` *two times:*
@@ -439,17 +439,17 @@ function Form() {
// ...
```
-This is why it works like declaring two separate state variables!
+This is why it works like declaring two separate State variables!
**Custom Hooks let you share *stateful logic* but not *state itself.* Each call to a Hook is completely independent from every other call to the same Hook.** This is why the two sandboxes above are completely equivalent. If you'd like, scroll back up and compare them. The behavior before and after extracting a custom Hook is identical.
-When you need to share the state itself between multiple components, [lift it up and pass it down](/learn/sharing-state-between-components) instead.
+When you need to share the State itself between multiple components, [lift it up and pass it down](/learn/sharing-state-between-components) instead.
## Passing reactive values between Hooks {/*passing-reactive-values-between-hooks*/}
The code inside your custom Hooks will re-run during every re-render of your component. This is why, like components, custom Hooks [need to be pure.](/learn/keeping-components-pure) Think of custom Hooks' code as part of your component's body!
-Because custom Hooks re-render together with your component, they always receive the latest props and state. To see what this means, consider this chat room example. Change the server URL or the chat room:
+Because custom Hooks re-render together with your component, they always receive the latest props and State. To see what this means, consider this chat room example. Change the server URL or the chat room:
@@ -645,7 +645,7 @@ export default function ChatRoom({ roomId }) {
This looks much simpler! (But it does the same thing.)
-Notice that the logic *still responds* to prop and state changes. Try editing the server URL or the selected room:
+Notice that the logic *still responds* to prop and State changes. Try editing the server URL or the selected room:
@@ -1890,7 +1890,7 @@ Sometimes, you don't even need a Hook!
#### Extract a `useCounter` Hook {/*extract-a-usecounter-hook*/}
-This component uses a state variable and an Effect to display a number that increments every second. Extract this logic into a custom Hook called `useCounter`. Your goal is to make the `Counter` component implementation look exactly like this:
+This component uses a State variable and an Effect to display a number that increments every second. Extract this logic into a custom Hook called `useCounter`. Your goal is to make the `Counter` component implementation look exactly like this:
```js
export default function Counter() {
@@ -1962,7 +1962,7 @@ Notice that `App.js` doesn't need to import `useState` or `useEffect` anymore.
#### Make the counter delay configurable {/*make-the-counter-delay-configurable*/}
-In this example, there is a `delay` state variable controlled by a slider, but its value is not used. Pass the `delay` value to your custom `useCounter` Hook, and change the `useCounter` Hook to use the passed `delay` instead of hardcoding `1000` ms.
+In this example, there is a `delay` State variable controlled by a slider, but its value is not used. Pass the `delay` value to your custom `useCounter` Hook, and change the `useCounter` Hook to use the passed `delay` instead of hardcoding `1000` ms.
@@ -2064,7 +2064,7 @@ export function useCounter(delay) {
#### Extract `useInterval` out of `useCounter` {/*extract-useinterval-out-of-usecounter*/}
-Currently, your `useCounter` Hook does two things. It sets up an interval, and it also increments a state variable on every interval tick. Split out the logic that sets up the interval into a separate Hook called `useInterval`. It should take two arguments: the `onTick` callback, and the `delay`. After this change, your `useCounter` implementation should look like this:
+Currently, your `useCounter` Hook does two things. It sets up an interval, and it also increments a State variable on every interval tick. Split out the logic that sets up the interval into a separate Hook called `useInterval`. It should take two arguments: the `onTick` callback, and the `delay`. After this change, your `useCounter` implementation should look like this:
```js
export function useCounter(delay) {
@@ -2327,7 +2327,7 @@ In this example, the `usePointerPosition()` Hook tracks the current pointer posi
In fact, there are five (!) different red dots being rendered. You don't see them because currently they all appear at the same position. This is what you need to fix. What you want to implement instead is a "staggered" movement: each dot should "follow" the previous dot's path. For example, if you quickly move your cursor, the first dot should follow it immediately, the second dot should follow the first dot with a small delay, the third dot should follow the second dot, and so on.
-You need to implement the `useDelayedValue` custom Hook. Its current implementation returns the `value` provided to it. Instead, you want to return the value back from `delay` milliseconds ago. You might need some state and an Effect to do this.
+You need to implement the `useDelayedValue` custom Hook. Its current implementation returns the `value` provided to it. Instead, you want to return the value back from `delay` milliseconds ago. You might need some State and an Effect to do this.
After you implement `useDelayedValue`, you should see the dots move following one another.
@@ -2408,7 +2408,7 @@ body { min-height: 300px; }
-Here is a working version. You keep the `delayedValue` as a state variable. When `value` updates, your Effect schedules a timeout to update the `delayedValue`. This is why the `delayedValue` always "lags behind" the actual `value`.
+Here is a working version. You keep the `delayedValue` as a State variable. When `value` updates, your Effect schedules a timeout to update the `delayedValue`. This is why the `delayedValue` always "lags behind" the actual `value`.
diff --git a/src/content/learn/scaling-up-with-reducer-and-context.md b/src/content/learn/scaling-up-with-reducer-and-context.md
index c3da0c6373d..be33da3b5ef 100644
--- a/src/content/learn/scaling-up-with-reducer-and-context.md
+++ b/src/content/learn/scaling-up-with-reducer-and-context.md
@@ -4,21 +4,21 @@ 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 avoid passing state and dispatch through props
-* How to keep context and state logic in a separate file
+* How to avoid passing State and dispatch through props
+* How to keep context and State logic in a separate file
## 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:
+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:
@@ -207,7 +207,7 @@ ul, li { margin: 0; padding: 0; }
-A reducer helps keep the event handlers short and concise. However, as your app grows, you might run into another difficulty. **Currently, the `tasks` state and the `dispatch` function are only available in the top-level `TaskApp` component.** To let other components read the list of tasks or change it, you have to explicitly [pass down](/learn/passing-props-to-a-component) the current state and the event handlers that change it as props.
+A reducer helps keep the event handlers short and concise. However, as your app grows, you might run into another difficulty. **Currently, the `tasks` State and the `dispatch` function are only available in the top-level `TaskApp` component.** To let other components read the list of tasks or change it, you have to explicitly [pass down](/learn/passing-props-to-a-component) the current State and the event handlers that change it as props.
For example, `TaskApp` passes a list of tasks and the event handlers to `TaskList`:
@@ -229,14 +229,14 @@ 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!
+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:
1. **Create** the context.
-2. **Put** state and dispatch into 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*/}
@@ -450,7 +450,7 @@ 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.
-### 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:
@@ -897,7 +897,7 @@ 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*/}
@@ -912,7 +912,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.
+1. It will manage the State with a reducer.
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.
@@ -1352,9 +1352,9 @@ As your app grows, you may have many context-reducer pairs like this. This is a
-- You can combine reducer with context to let any component read and update state above it.
-- To provide state and the dispatch function to components below:
- 1. Create two contexts (for state and for dispatch functions).
+- 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.
- You can further declutter the components by moving all wiring into one file.
diff --git a/src/content/learn/separating-events-from-effects.md b/src/content/learn/separating-events-from-effects.md
index ac65d2b6071..2823244f283 100644
--- a/src/content/learn/separating-events-from-effects.md
+++ b/src/content/learn/separating-events-from-effects.md
@@ -4,7 +4,7 @@ title: 'Separating Events from Effects'
-Event handlers only re-run when you perform the same interaction again. Unlike event handlers, Effects re-synchronize if some value they read, like a prop or a state variable, is different from what it was during the last render. Sometimes, you also want a mix of both behaviors: an Effect that re-runs in response to some values but not others. This page will teach you how to do that.
+Event handlers only re-run when you perform the same interaction again. Unlike event handlers, Effects re-synchronize if some value they read, like a prop or a State variable, is different from what it was during the last render. Sometimes, you also want a mix of both behaviors: an Effect that re-runs in response to some values but not others. This page will teach you how to do that.
@@ -14,7 +14,7 @@ Event handlers only re-run when you perform the same interaction again. Unlike e
- Why Effects are reactive, and event handlers are not
- What to do when you want a part of your Effect's code to not be reactive
- What Effect Events are, and how to extract them from your Effects
-- How to read the latest props and state from Effects using Effect Events
+- How to read the latest props and State from Effects using Effect Events
@@ -160,7 +160,7 @@ Intuitively, you could say that event handlers are always triggered "manually",
There is a more precise way to think about this.
-Props, state, and variables declared inside your component's body are called reactive values. In this example, `serverUrl` is not a reactive value, but `roomId` and `message` are. They participate in the rendering data flow:
+Props, State, and variables declared inside your component's body are called reactive values. In this example, `serverUrl` is not a reactive value, but `roomId` and `message` are. They participate in the rendering data flow:
```js [[2, 3, "roomId"], [2, 4, "message"]]
const serverUrl = 'https://localhost:1234';
@@ -418,7 +418,7 @@ function ChatRoom({ roomId, theme }) {
// ...
```
-Here, `onConnected` is called an *Effect Event.* It's a part of your Effect logic, but it behaves a lot more like an event handler. The logic inside it is not reactive, and it always "sees" the latest values of your props and state.
+Here, `onConnected` is called an *Effect Event.* It's a part of your Effect logic, but it behaves a lot more like an event handler. The logic inside it is not reactive, and it always "sees" the latest values of your props and State.
Now you can call the `onConnected` Effect Event from inside your Effect:
@@ -576,7 +576,7 @@ label { display: block; margin-top: 10px; }
You can think of Effect Events as being very similar to event handlers. The main difference is that event handlers run in response to a user interactions, whereas Effect Events are triggered by you from Effects. Effect Events let you "break the chain" between the reactivity of Effects and code that should not be reactive.
-### Reading latest props and state with Effect Events {/*reading-latest-props-and-state-with-effect-events*/}
+### Reading latest props and State with Effect Events {/*reading-latest-props-and-state-with-effect-events*/}
@@ -729,7 +729,7 @@ After `useEffectEvent` becomes a stable part of React, we recommend **never supp
The first downside of suppressing the rule is that React will no longer warn you when your Effect needs to "react" to a new reactive dependency you've introduced to your code. In the earlier example, you added `url` to the dependencies *because* React reminded you to do it. You will no longer get such reminders for any future edits to that Effect if you disable the linter. This leads to bugs.
-Here is an example of a confusing bug caused by suppressing the linter. In this example, the `handleMove` function is supposed to read the current `canMove` state variable value in order to decide whether the dot should follow the cursor. However, `canMove` is always `true` inside `handleMove`.
+Here is an example of a confusing bug caused by suppressing the linter. In this example, the `handleMove` function is supposed to read the current `canMove` State variable value in order to decide whether the dot should follow the cursor. However, `canMove` is always `true` inside `handleMove`.
Can you see why?
@@ -961,7 +961,7 @@ Effect Events are non-reactive "pieces" of your Effect code. They should be next
#### Fix a variable that doesn't update {/*fix-a-variable-that-doesnt-update*/}
-This `Timer` component keeps a `count` state variable which increases every second. The value by which it's increasing is stored in the `increment` state variable. You can control the `increment` variable with the plus and minus buttons.
+This `Timer` component keeps a `count` State variable which increases every second. The value by which it's increasing is stored in the `increment` State variable. You can control the `increment` variable with the plus and minus buttons.
However, no matter how many times you click the plus button, the counter is still incremented by one every second. What's wrong with this code? Why is `increment` always equal to `1` inside the Effect's code? Find the mistake and fix it.
@@ -1076,7 +1076,7 @@ Now, when `increment` changes, React will re-synchronize your Effect, which will
#### Fix a freezing counter {/*fix-a-freezing-counter*/}
-This `Timer` component keeps a `count` state variable which increases every second. The value by which it's increasing is stored in the `increment` state variable, which you can control it with the plus and minus buttons. For example, try pressing the plus button nine times, and notice that the `count` now increases each second by ten rather than by one.
+This `Timer` component keeps a `count` State variable which increases every second. The value by which it's increasing is stored in the `increment` State variable, which you can control it with the plus and minus buttons. For example, try pressing the plus button nine times, and notice that the `count` now increases each second by ten rather than by one.
There is a small issue with this user interface. You might notice that if you keep pressing the plus or minus buttons faster than once per second, the timer itself seems to pause. It only resumes after a second passes since the last time you've pressed either button. Find why this is happening, and fix the issue so that the timer ticks on *every* second without interruptions.
@@ -1151,7 +1151,7 @@ button { margin: 10px; }
-The issue is that the code inside the Effect uses the `increment` state variable. Since it's a dependency of your Effect, every change to `increment` causes the Effect to re-synchronize, which causes the interval to clear. If you keep clearing the interval every time before it has a chance to fire, it will appear as if the timer has stalled.
+The issue is that the code inside the Effect uses the `increment` State variable. Since it's a dependency of your Effect, every change to `increment` causes the Effect to re-synchronize, which causes the interval to clear. If you keep clearing the interval every time before it has a chance to fire, it will appear as if the timer has stalled.
To solve the issue, extract an `onTick` Effect Event from the Effect:
@@ -1229,7 +1229,7 @@ Since `onTick` is an Effect Event, the code inside it isn't reactive. The change
#### Fix a non-adjustable delay {/*fix-a-non-adjustable-delay*/}
-In this example, you can customize the interval delay. It's stored in a `delay` state variable which is updated by two buttons. However, even if you press the "plus 100 ms" button until the `delay` is 1000 milliseconds (that is, a second), you'll notice that the timer still increments very fast (every 100 ms). It's as if your changes to the `delay` are ignored. Find and fix the bug.
+In this example, you can customize the interval delay. It's stored in a `delay` State variable which is updated by two buttons. However, even if you press the "plus 100 ms" button until the `delay` is 1000 milliseconds (that is, a second), you'll notice that the timer still increments very fast (every 100 ms). It's as if your changes to the `delay` are ignored. Find and fix the bug.
@@ -1322,7 +1322,7 @@ button { margin: 10px; }
-The problem with the above example is that it extracted an Effect Event called `onMount` without considering what the code should actually be doing. You should only extract Effect Events for a specific reason: when you want to make a part of your code non-reactive. However, the `setInterval` call *should* be reactive with respect to the `delay` state variable. If the `delay` changes, you want to set up the interval from scratch! To fix this code, pull all the reactive code back inside the Effect:
+The problem with the above example is that it extracted an Effect Event called `onMount` without considering what the code should actually be doing. You should only extract Effect Events for a specific reason: when you want to make a part of your code non-reactive. However, the `setInterval` call *should* be reactive with respect to the `delay` State variable. If the `delay` changes, you want to set up the interval from scratch! To fix this code, pull all the reactive code back inside the Effect:
diff --git a/src/content/learn/sharing-state-between-components.md b/src/content/learn/sharing-state-between-components.md
index 52eaf28f85d..076633cb53f 100644
--- a/src/content/learn/sharing-state-between-components.md
+++ b/src/content/learn/sharing-state-between-components.md
@@ -4,18 +4,18 @@ title: Sharing State Between Components
-Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as *lifting state up,* and it's one of the most common things you will do writing React code.
+Sometimes, you want the State of two components to always change together. To do it, remove State from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as *lifting State up,* and it's one of the most common things you will do writing React code.
-- How to share state between components by lifting it up
+- How to share State between components by lifting it up
- What are controlled and uncontrolled components
-## Lifting state up by example {/*lifting-state-up-by-example*/}
+## Lifting State up by example {/*lifting-state-up-by-example*/}
In this example, a parent `Accordion` component renders two separate `Panel`s:
@@ -23,7 +23,7 @@ In this example, a parent `Accordion` component renders two separate `Panel`s:
- `Panel`
- `Panel`
-Each `Panel` component has a boolean `isActive` state that determines whether its content is visible.
+Each `Panel` component has a boolean `isActive` State that determines whether its content is visible.
Press the Show button for both panels:
@@ -79,13 +79,13 @@ Notice how pressing one panel's button does not affect the other panel--they are
-Initially, each `Panel`'s `isActive` state is `false`, so they both appear collapsed
+Initially, each `Panel`'s `isActive` State is `false`, so they both appear collapsed
-Clicking either `Panel`'s button will only update that `Panel`'s `isActive` state alone
+Clicking either `Panel`'s button will only update that `Panel`'s `isActive` State alone
@@ -93,15 +93,15 @@ Clicking either `Panel`'s button will only update that `Panel`'s `isActive` stat
**But now let's say you want to change it so that only one panel is expanded at any given time.** With that design, expanding the second panel should collapse the first one. How would you do that?
-To coordinate these two panels, you need to "lift their state up" to a parent component in three steps:
+To coordinate these two panels, you need to "lift their State up" to a parent component in three steps:
-1. **Remove** state from the child components.
+1. **Remove** State from the child components.
2. **Pass** hardcoded data from the common parent.
-3. **Add** state to the common parent and pass it down together with the event handlers.
+3. **Add** State to the common parent and pass it down together with the event handlers.
This will allow the `Accordion` component to coordinate both `Panel`s and only expand one at a time.
-### Step 1: Remove state from the child components {/*step-1-remove-state-from-the-child-components*/}
+### Step 1: Remove State from the child components {/*step-1-remove-state-from-the-child-components*/}
You will give control of the `Panel`'s `isActive` to its parent component. This means that the parent component will pass `isActive` to `Panel` as a prop instead. Start by **removing this line** from the `Panel` component:
@@ -119,7 +119,7 @@ Now the `Panel`'s parent component can *control* `isActive` by [passing it down
### Step 2: Pass hardcoded data from the common parent {/*step-2-pass-hardcoded-data-from-the-common-parent*/}
-To lift state up, you must locate the closest common parent component of *both* of the child components that you want to coordinate:
+To lift State up, you must locate the closest common parent component of *both* of the child components that you want to coordinate:
* `Accordion` *(closest common parent)*
- `Panel`
@@ -174,11 +174,11 @@ h3, p { margin: 5px 0px; }
Try editing the hardcoded `isActive` values in the `Accordion` component and see the result on the screen.
-### Step 3: Add state to the common parent {/*step-3-add-state-to-the-common-parent*/}
+### Step 3: Add State to the common parent {/*step-3-add-state-to-the-common-parent*/}
-Lifting state up often changes the nature of what you're storing as state.
+Lifting State up often changes the nature of what you're storing as State.
-In this case, only one panel should be active at a time. This means that the `Accordion` common parent component needs to keep track of *which* panel is the active one. Instead of a `boolean` value, it could use a number as the index of the active `Panel` for the state variable:
+In this case, only one panel should be active at a time. This means that the `Accordion` common parent component needs to keep track of *which* panel is the active one. Instead of a `boolean` value, it could use a number as the index of the active `Panel` for the State variable:
```js
const [activeIndex, setActiveIndex] = useState(0);
@@ -186,7 +186,7 @@ const [activeIndex, setActiveIndex] = useState(0);
When the `activeIndex` is `0`, the first panel is active, and when it's `1`, it's the second one.
-Clicking the "Show" button in either `Panel` needs to change the active index in `Accordion`. A `Panel` can't set the `activeIndex` state directly because it's defined inside the `Accordion`. The `Accordion` component needs to *explicitly allow* the `Panel` component to change its state by [passing an event handler down as a prop](/learn/responding-to-events#passing-event-handlers-as-props):
+Clicking the "Show" button in either `Panel` needs to change the active index in `Accordion`. A `Panel` can't set the `activeIndex` State directly because it's defined inside the `Accordion`. The `Accordion` component needs to *explicitly allow* the `Panel` component to change its State by [passing an event handler down as a prop](/learn/responding-to-events#passing-event-handlers-as-props):
```js
<>
@@ -266,7 +266,7 @@ h3, p { margin: 5px 0px; }
-This completes lifting state up! Moving state into the common parent component allowed you to coordinate the two panels. Using the active index instead of two "is shown" flags ensured that only one panel is active at a given time. And passing down the event handler to the child allowed the child to change the parent's state.
+This completes lifting State up! Moving State into the common parent component allowed you to coordinate the two panels. Using the active index instead of two "is shown" flags ensured that only one panel is active at a given time. And passing down the event handler to the child allowed the child to change the parent's State.
@@ -278,7 +278,7 @@ Initially, `Accordion`'s `activeIndex` is `0`, so the first `Panel` receives `is
-When `Accordion`'s `activeIndex` state changes to `1`, the second `Panel` receives `isActive = true` instead
+When `Accordion`'s `activeIndex` State changes to `1`, the second `Panel` receives `isActive = true` instead
@@ -288,34 +288,34 @@ When `Accordion`'s `activeIndex` state changes to `1`, the second `Panel` receiv
#### Controlled and uncontrolled components {/*controlled-and-uncontrolled-components*/}
-It is common to call a component with some local state "uncontrolled". For example, the original `Panel` component with an `isActive` state variable is uncontrolled because its parent cannot influence whether the panel is active or not.
+It is common to call a component with some local State "uncontrolled". For example, the original `Panel` component with an `isActive` State variable is uncontrolled because its parent cannot influence whether the panel is active or not.
-In contrast, you might say a component is "controlled" when the important information in it is driven by props rather than its own local state. This lets the parent component fully specify its behavior. The final `Panel` component with the `isActive` prop is controlled by the `Accordion` component.
+In contrast, you might say a component is "controlled" when the important information in it is driven by props rather than its own local State. This lets the parent component fully specify its behavior. The final `Panel` component with the `isActive` prop is controlled by the `Accordion` component.
Uncontrolled components are easier to use within their parents because they require less configuration. But they're less flexible when you want to coordinate them together. Controlled components are maximally flexible, but they require the parent components to fully configure them with props.
-In practice, "controlled" and "uncontrolled" aren't strict technical terms--each component usually has some mix of both local state and props. However, this is a useful way to talk about how components are designed and what capabilities they offer.
+In practice, "controlled" and "uncontrolled" aren't strict technical terms--each component usually has some mix of both local State and props. However, this is a useful way to talk about how components are designed and what capabilities they offer.
-When writing a component, consider which information in it should be controlled (via props), and which information should be uncontrolled (via state). But you can always change your mind and refactor later.
+When writing a component, consider which information in it should be controlled (via props), and which information should be uncontrolled (via State). But you can always change your mind and refactor later.
-## A single source of truth for each state {/*a-single-source-of-truth-for-each-state*/}
+## 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.
+**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.
-Your app will change as you work on it. It is common that you will move state down or back up while you're still figuring out where each piece of the state "lives". This is all part of the process!
+Your app will change as you work on it. It is common that you will move State down or back up while you're still figuring out where each piece of the State "lives". This is all part of the process!
To see what this feels like in practice with a few more components, read [Thinking in React.](/learn/thinking-in-react)
-* When you want to coordinate two components, move their state to their common parent.
+* When you want to coordinate two components, move their State to their common parent.
* Then pass the information down through props from their common parent.
-* Finally, pass the event handlers down so that the children can change the parent's state.
-* It's useful to consider components as "controlled" (driven by props) or "uncontrolled" (driven by state).
+* Finally, pass the event handlers down so that the children can change the parent's State.
+* It's useful to consider components as "controlled" (driven by props) or "uncontrolled" (driven by State).
@@ -327,7 +327,7 @@ These two inputs are independent. Make them stay in sync: editing one input shou
-You'll need to lift their state up into the parent component.
+You'll need to lift their State up into the parent component.
@@ -374,7 +374,7 @@ label { display: block; }
-Move the `text` state variable into the parent component along with the `handleChange` handler. Then pass them down as props to both of the `Input` components. This will keep them in sync.
+Move the `text` State variable into the parent component along with the `handleChange` handler. Then pass them down as props to both of the `Input` components. This will keep them in sync.
@@ -429,7 +429,7 @@ label { display: block; }
#### Filtering a list {/*filtering-a-list*/}
-In this example, the `SearchBar` has its own `query` state that controls the text input. Its parent `FilterableList` component displays a `List` of items, but it doesn't take the search query into account.
+In this example, the `SearchBar` has its own `query` State that controls the text input. Its parent `FilterableList` component displays a `List` of items, but it doesn't take the search query into account.
Use the `filterItems(foods, query)` function to filter the list according to the search query. To test your changes, verify that typing "s" into the input filters down the list to "Sushi", "Shish kebab", and "Dim sum".
@@ -437,7 +437,7 @@ Note that `filterItems` is already implemented and imported so you don't need to
-You will want to remove the `query` state and the `handleChange` handler from the `SearchBar`, and move them to the `FilterableList`. Then pass them down to `SearchBar` as `query` and `onChange` props.
+You will want to remove the `query` State and the `handleChange` handler from the `SearchBar`, and move them to the `FilterableList`. Then pass them down to `SearchBar` as `query` and `onChange` props.
@@ -528,7 +528,7 @@ export const foods = [{
-Lift the `query` state up into the `FilterableList` component. Call `filterItems(foods, query)` to get the filtered list and pass it down to the `List`. Now changing the query input is reflected in the list:
+Lift the `query` State up into the `FilterableList` component. Call `filterItems(foods, query)` to get the filtered list and pass it down to the `List`. Now changing the query input is reflected in the list:
diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index 75a1fd0b91e..a89b891af2b 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -4,16 +4,16 @@ title: "State: A Component's Memory"
-Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" should put a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state*.
+Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" should put a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *State*.
-* How to add a state variable with the [`useState`](/reference/react/useState) Hook
+* How to add a State variable with the [`useState`](/reference/react/useState) Hook
* What pair of values the `useState` Hook returns
-* How to add more than one state variable
-* Why state is called local
+* How to add more than one State variable
+* Why State is called local
@@ -163,12 +163,12 @@ To update a component with new data, two things need to happen:
The [`useState`](/reference/react/useState) Hook provides those two things:
-1. A **state variable** to retain the data between renders.
-2. A **state setter function** to update the variable and trigger React to render the component again.
+1. A **State variable** to retain the data between renders.
+2. A **State setter function** to update the variable and trigger React to render the component again.
-## Adding a state variable {/*adding-a-state-variable*/}
+## Adding a State variable {/*adding-a-state-variable*/}
-To add a state variable, import `useState` from React at the top of the file:
+To add a State variable, import `useState` from React at the top of the file:
```js
import { useState } from 'react';
@@ -186,7 +186,7 @@ with
const [index, setIndex] = useState(0);
```
-`index` is a state variable and `setIndex` is the setter function.
+`index` is a State variable and `setIndex` is the setter function.
> The `[` and `]` syntax here is called [array destructuring](https://javascript.info/destructuring-assignment) and it lets you read values from an array. The array returned by `useState` always has exactly two items.
@@ -361,12 +361,12 @@ The convention is to name this pair like `const [something, setSomething]`. You
-The only argument to `useState` is the **initial value** of your state variable. In this example, the `index`'s initial value is set to `0` with `useState(0)`.
+The only argument to `useState` is the **initial value** of your State variable. In this example, the `index`'s initial value is set to `0` with `useState(0)`.
Every time your component renders, `useState` gives you an array containing two values:
-1. The **state variable** (`index`) with the value you stored.
-2. The **state setter function** (`setIndex`) which can update the state variable and trigger React to render the component again.
+1. The **State variable** (`index`) with the value you stored.
+2. The **State setter function** (`setIndex`) which can update the State variable and trigger React to render the component again.
Here's how that happens in action:
@@ -374,14 +374,14 @@ Here's how that happens in action:
const [index, setIndex] = useState(0);
```
-1. **Your component renders the first time.** Because you passed `0` to `useState` as the initial value for `index`, it will return `[0, setIndex]`. React remembers `0` is the latest state value.
-2. **You update the state.** When a user clicks the button, it calls `setIndex(index + 1)`. `index` is `0`, so it's `setIndex(1)`. This tells React to remember `index` is `1` now and triggers another render.
+1. **Your component renders the first time.** Because you passed `0` to `useState` as the initial value for `index`, it will return `[0, setIndex]`. React remembers `0` is the latest State value.
+2. **You update the State.** When a user clicks the button, it calls `setIndex(index + 1)`. `index` is `0`, so it's `setIndex(1)`. This tells React to remember `index` is `1` now and triggers another render.
3. **Your component's second render.** React still sees `useState(0)`, but because React *remembers* that you set `index` to `1`, it returns `[1, setIndex]` instead.
4. And so on!
-## Giving a component multiple state variables {/*giving-a-component-multiple-state-variables*/}
+## Giving a component multiple State variables {/*giving-a-component-multiple-state-variables*/}
-You can have as many state variables of as many types as you like in one component. This component has two state variables, a number `index` and a boolean `showMore` that's toggled when you click "Show details":
+You can have as many State variables of as many types as you like in one component. This component has two State variables, a number `index` and a boolean `showMore` that's toggled when you click "Show details":
@@ -520,17 +520,17 @@ button {
-It is a good idea to have multiple state variables if their state is unrelated, like `index` and `showMore` in this example. But if you find that you often change two state variables together, it might be easier to combine them into one. For example, if you have a form with many fields, it's more convenient to have a single state variable that holds an object than state variable per field. Read [Choosing the State Structure](/learn/choosing-the-state-structure) for more tips.
+It is a good idea to have multiple State variables if their State is unrelated, like `index` and `showMore` in this example. But if you find that you often change two State variables together, it might be easier to combine them into one. For example, if you have a form with many fields, it's more convenient to have a single State variable that holds an object than State variable per field. Read [Choosing the State Structure](/learn/choosing-the-state-structure) for more tips.
-#### How does React know which state to return? {/*how-does-react-know-which-state-to-return*/}
+#### How does React know which State to return? {/*how-does-react-know-which-state-to-return*/}
-You might have noticed that the `useState` call does not receive any information about *which* state variable it refers to. There is no "identifier" that is passed to `useState`, so how does it know which of the state variables to return? Does it rely on some magic like parsing your functions? The answer is no.
+You might have noticed that the `useState` call does not receive any information about *which* State variable it refers to. There is no "identifier" that is passed to `useState`, so how does it know which of the State variables to return? Does it rely on some magic like parsing your functions? The answer is no.
Instead, to enable their concise syntax, Hooks **rely on a stable call order on every render of the same component.** This works well in practice because if you follow the rule above ("only call Hooks at the top level"), Hooks will always be called in the same order. Additionally, a [linter plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) catches most mistakes.
-Internally, React holds an array of state pairs for every component. It also maintains the current pair index, which is set to `0` before rendering. Each time you call `useState`, React gives you the next state pair and increments the index. You can read more about this mechanism in [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
+Internally, React holds an array of State pairs for every component. It also maintains the current pair index, which is set to `0` before rendering. Each time you call `useState`, React gives you the next State pair and increments the index. You can read more about this mechanism in [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
This example **doesn't use React** but it gives you an idea of how `useState` works internally:
@@ -732,7 +732,7 @@ You don't have to understand it to use React, but you might find this a helpful
State is local to a component instance on the screen. In other words, **if you render the same component twice, each copy will have completely isolated state!** Changing one of them will not affect the other.
-In this example, the `Gallery` component from earlier is rendered twice with no changes to its logic. Try clicking the buttons inside each of the galleries. Notice that their state is independent:
+In this example, the `Gallery` component from earlier is rendered twice with no changes to its logic. Try clicking the buttons inside each of the galleries. Notice that their State is independent:
@@ -891,21 +891,21 @@ button {
-This is what makes state different from regular variables that you might declare at the top of your module. State is not tied to a particular function call or a place in the code, but it's "local" to the specific place on the screen. You rendered two `` components, so their state is stored separately.
+This is what makes State different from regular variables that you might declare at the top of your module. State is not tied to a particular function call or a place in the code, but it's "local" to the specific place on the screen. You rendered two `` components, so their State is stored separately.
-Also notice how the `Page` component doesn't "know" anything about the `Gallery` state or even whether it has any. Unlike props, **state is fully private to the component declaring it.** The parent component can't change it. This lets you add state to any component or remove it without impacting the rest of the components.
+Also notice how the `Page` component doesn't "know" anything about the `Gallery` State or even whether it has any. Unlike props, **State is fully private to the component declaring it.** The parent component can't change it. This lets you add State to any component or remove it without impacting the rest of the components.
-What if you wanted both galleries to keep their states in sync? The right way to do it in React is to *remove* state from child components and add it to their closest shared parent. The next few pages will focus on organizing state of a single component, but we will return to this topic in [Sharing State Between Components.](/learn/sharing-state-between-components)
+What if you wanted both galleries to keep their States in sync? The right way to do it in React is to *remove* State from child components and add it to their closest shared parent. The next few pages will focus on organizing State of a single component, but we will return to this topic in [Sharing State Between Components.](/learn/sharing-state-between-components)
-* Use a state variable when a component needs to "remember" some information between renders.
+* Use a State variable when a component needs to "remember" some information between renders.
* State variables are declared by calling the `useState` Hook.
-* Hooks are special functions that start with `use`. They let you "hook into" React features like state.
+* Hooks are special functions that start with `use`. They let you "hook into" React features like State.
* Hooks might remind you of imports: they need to be called unconditionally. Calling Hooks, including `useState`, is only valid at the top level of a component or another Hook.
-* The `useState` Hook returns a pair of values: the current state and the function to update it.
-* You can have more than one state variable. Internally, React matches them up by their order.
-* State is private to the component. If you render it in two places, each copy gets its own state.
+* The `useState` Hook returns a pair of values: the current State and the function to update it.
+* You can have more than one State variable. Internally, React matches them up by their order.
+* State is private to the component. If you render it in two places, each copy gets its own State.
@@ -1225,7 +1225,7 @@ Notice how `hasPrev` and `hasNext` are used *both* for the returned JSX and insi
#### Fix stuck form inputs {/*fix-stuck-form-inputs*/}
-When you type into the input fields, nothing appears. It's like the input values are "stuck" with empty strings. The `value` of the first `` is set to always match the `firstName` variable, and the `value` for the second `` is set to always match the `lastName` variable. This is correct. Both inputs have `onChange` event handlers, which try to update the variables based on the latest user input (`e.target.value`). However, the variables don't seem to "remember" their values between re-renders. Fix this by using state variables instead.
+When you type into the input fields, nothing appears. It's like the input values are "stuck" with empty strings. The `value` of the first `` is set to always match the `firstName` variable, and the `value` for the second `` is set to always match the `lastName` variable. This is correct. Both inputs have `onChange` event handlers, which try to update the variables based on the latest user input (`e.target.value`). However, the variables don't seem to "remember" their values between re-renders. Fix this by using State variables instead.
@@ -1274,7 +1274,7 @@ h1 { margin-top: 10px; }
-First, import `useState` from React. Then replace `firstName` and `lastName` with state variables declared by calling `useState`. Finally, replace every `firstName = ...` assignment with `setFirstName(...)`, and do the same for `lastName`. Don't forget to update `handleReset` too so that the reset button works.
+First, import `useState` from React. Then replace `firstName` and `lastName` with State variables declared by calling `useState`. Finally, replace every `firstName = ...` assignment with `setFirstName(...)`, and do the same for `lastName`. Don't forget to update `handleReset` too so that the reset button works.
@@ -1450,13 +1450,13 @@ If your linter is [configured for React](/learn/editor-setup#linting), you shoul
-#### Remove unnecessary state {/*remove-unnecessary-state*/}
+#### Remove unnecessary State {/*remove-unnecessary-state*/}
-When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use state to keep the name, but for some reason it always shows "Hello, !".
+When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use State to keep the name, but for some reason it always shows "Hello, !".
-To fix this code, remove the unnecessary state variable. (We will discuss about [why this didn't work](/learn/state-as-a-snapshot) later.)
+To fix this code, remove the unnecessary State variable. (We will discuss about [why this didn't work](/learn/state-as-a-snapshot) later.)
-Can you explain why this state variable was unnecessary?
+Can you explain why this State variable was unnecessary?
@@ -1504,7 +1504,7 @@ export default function FeedbackForm() {
-A state variable is only necessary to keep information between re-renders of a component. Within a single event handler, a regular variable will do fine. Don't introduce state variables when a regular variable works well.
+A State variable is only necessary to keep information between re-renders of a component. Within a single event handler, a regular variable will do fine. Don't introduce State variables when a regular variable works well.
diff --git a/src/content/learn/state-as-a-snapshot.md b/src/content/learn/state-as-a-snapshot.md
index df4eddbd677..67da7a85757 100644
--- a/src/content/learn/state-as-a-snapshot.md
+++ b/src/content/learn/state-as-a-snapshot.md
@@ -4,22 +4,22 @@ title: State as a Snapshot
-State variables might look like regular JavaScript variables that you can read and write to. However, state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render.
+State variables might look like regular JavaScript variables that you can read and write to. However, State behaves more like a snapshot. Setting it does not change the State variable you already have, but instead triggers a re-render.
-* How setting state triggers re-renders
-* When and how state updates
-* Why state does not update immediately after you set it
-* How event handlers access a "snapshot" of the state
+* How setting State triggers re-renders
+* When and how State updates
+* Why State does not update immediately after you set it
+* How event handlers access a "snapshot" of the State
-## Setting state triggers renders {/*setting-state-triggers-renders*/}
+## Setting State triggers renders {/*setting-state-triggers-renders*/}
-You might think of your user interface as changing directly in response to the user event like a click. In React, it works a little differently from this mental model. On the previous page, you saw that [setting state requests a re-render](/learn/render-and-commit#step-1-trigger-a-render) from React. This means that for an interface to react to the event, you need to *update the state*.
+You might think of your user interface as changing directly in response to the user event like a click. In React, it works a little differently from this mental model. On the previous page, you saw that [setting State requests a re-render](/learn/render-and-commit#step-1-trigger-a-render) from React. This means that for an interface to react to the event, you need to *update the State*.
In this example, when you press "send", `setIsSent(true)` tells React to re-render the UI:
@@ -67,11 +67,11 @@ Here's what happens when you click the button:
2. `setIsSent(true)` sets `isSent` to `true` and queues a new render.
3. React re-renders the component according to the new `isSent` value.
-Let's take a closer look at the relationship between state and rendering.
+Let's take a closer look at the relationship between State and rendering.
## Rendering takes a snapshot in time {/*rendering-takes-a-snapshot-in-time*/}
-["Rendering"](/learn/render-and-commit#step-2-react-renders-your-components) means that React is calling your component, which is a function. The JSX you return from that function is like a snapshot of the UI in time. Its props, event handlers, and local variables were all calculated **using its state at the time of the render.**
+["Rendering"](/learn/render-and-commit#step-2-react-renders-your-components) means that React is calling your component, which is a function. The JSX you return from that function is like a snapshot of the UI in time. Its props, event handlers, and local variables were all calculated **using its State at the time of the render.**
Unlike a photograph or a movie frame, the UI "snapshot" you return is interactive. It includes logic like event handlers that specify what happens in response to inputs. React updates the screen to match this snapshot and connects the event handlers. As a result, pressing a button will trigger the click handler from your JSX.
@@ -87,7 +87,7 @@ When React re-renders a component:
-As a component's memory, state is not like a regular variable that disappears after your function returns. State actually "lives" in React itself--as if on a shelf!--outside of your function. When React calls your component, it gives you a snapshot of the state for that particular render. Your component returns a snapshot of the UI with a fresh set of props and event handlers in its JSX, all calculated **using the state values from that render!**
+As a component's memory, State is not like a regular variable that disappears after your function returns. State actually "lives" in React itself--as if on a shelf!--outside of your function. When React calls your component, it gives you a snapshot of the State for that particular render. Your component returns a snapshot of the UI with a fresh set of props and event handlers in its JSX, all calculated **using the State values from that render!**
@@ -129,7 +129,7 @@ h1 { display: inline-block; margin: 10px; width: 30px; text-align: center; }
Notice that `number` only increments once per click!
-**Setting state only changes it for the *next* render.** During the first render, `number` was `0`. This is why, in *that render's* `onClick` handler, the value of `number` is still `0` even after `setNumber(number + 1)` was called:
+**Setting State only changes it for the *next* render.** During the first render, `number` was `0`. This is why, in *that render's* `onClick` handler, the value of `number` is still `0` even after `setNumber(number + 1)` was called:
```js
-Surprised? If you use the substitution method, you can see the "snapshot" of the state passed to the alert.
+Surprised? If you use the substitution method, you can see the "snapshot" of the State passed to the alert.
```js
setNumber(0 + 5);
@@ -250,9 +250,9 @@ setTimeout(() => {
}, 3000);
```
-The state stored in React may have changed by the time the alert runs, but it was scheduled using a snapshot of the state at the time the user interacted with it!
+The State stored in React may have changed by the time the alert runs, but it was scheduled using a snapshot of the State at the time the user interacted with it!
-**A state variable's value never changes within a render,** even if its event handler's code is asynchronous. Inside *that render's* `onClick`, the value of `number` continues to be `0` even after `setNumber(number + 5)` was called. Its value was "fixed" when React "took the snapshot" of the UI by calling your component.
+**A State variable's value never changes within a render,** even if its event handler's code is asynchronous. Inside *that render's* `onClick`, the value of `number` continues to be `0` even after `setNumber(number + 5)` was called. Its value was "fixed" when React "took the snapshot" of the UI by calling your component.
Here is an example of how that makes your event handlers less prone to timing mistakes. Below is a form that sends a message with a five-second delay. Imagine this scenario:
@@ -305,19 +305,19 @@ label, textarea { margin-bottom: 10px; display: block; }
-**React keeps the state values "fixed" within one render's event handlers.** You don't need to worry whether the state has changed while the code is running.
+**React keeps the State values "fixed" within one render's event handlers.** You don't need to worry whether the State has changed while the code is running.
-But what if you wanted to read the latest state before a re-render? You'll want to use a [state updater function](/learn/queueing-a-series-of-state-updates), covered on the next page!
+But what if you wanted to read the latest State before a re-render? You'll want to use a [State updater function](/learn/queueing-a-series-of-state-updates), covered on the next page!
-* Setting state requests a new render.
-* React stores state outside of your component, as if on a shelf.
-* When you call `useState`, React gives you a snapshot of the state *for that render*.
+* Setting State requests a new render.
+* React stores State outside of your component, as if on a shelf.
+* When you call `useState`, React gives you a snapshot of the State *for that render*.
* Variables and event handlers don't "survive" re-renders. Every render has its own event handlers.
-* Every render (and functions inside it) will always "see" the snapshot of the state that React gave to *that* render.
-* You can mentally substitute state in event handlers, similarly to how you think about the rendered JSX.
-* Event handlers created in the past have the state values from the render in which they were created.
+* Every render (and functions inside it) will always "see" the snapshot of the State that React gave to *that* render.
+* You can mentally substitute State in event handlers, similarly to how you think about the rendered JSX.
+* Event handlers created in the past have the State values from the render in which they were created.
diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md
index f1aa9843849..1bfb0232126 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.
@@ -22,7 +22,7 @@ Some components need to synchronize with external systems. For example, you migh
Before getting to Effects, you need to be familiar with two types of logic inside React components:
-- **Rendering code** (introduced in [Describing the UI](/learn/describing-the-ui)) lives at the top level of your component. This is where you take the props and state, transform them, and return the JSX you want to see on the screen. [Rendering code must be pure.](/learn/keeping-components-pure) Like a math formula, it should only _calculate_ the result, but not do anything else.
+- **Rendering code** (introduced in [Describing the UI](/learn/describing-the-ui)) lives at the top level of your component. This is where you take the props and State, transform them, and return the JSX you want to see on the screen. [Rendering code must be pure.](/learn/keeping-components-pure) Like a math formula, it should only _calculate_ the result, but not do anything else.
- **Event handlers** (introduced in [Adding Interactivity](/learn/adding-interactivity)) are nested functions inside your components that *do* things rather than just calculate them. An event handler might update an input field, submit an HTTP POST request to buy a product, or navigate the user to another screen. Event handlers contain ["side effects"](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) (they change the program's state) caused by a specific user action (for example, a button click or typing).
@@ -39,7 +39,7 @@ Here and later in this text, capitalized "Effect" refers to the React-specific d
## You might not need an Effect {/*you-might-not-need-an-effect*/}
-**Don't rush to add Effects to your components.** Keep in mind that Effects are typically used to "step out" of your React code and synchronize with some *external* system. This includes browser APIs, third-party widgets, network, and so on. If your Effect only adjusts some state based on other state, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
+**Don't rush to add Effects to your components.** Keep in mind that Effects are typically used to "step out" of your React code and synchronize with some *external* system. This includes browser APIs, third-party widgets, network, and so on. If your Effect only adjusts some State based on other State, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
## How to write an Effect {/*how-to-write-an-effect*/}
@@ -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.
@@ -220,9 +220,9 @@ useEffect(() => {
});
```
-Effects run as a *result* of rendering. Setting state *triggers* rendering. Setting state immediately in an Effect is like plugging a power outlet into itself. The Effect runs, it sets the state, which causes a re-render, which causes the Effect to run, it sets the state again, this causes another re-render, and so on.
+Effects run as a *result* of rendering. Setting State *triggers* rendering. Setting State immediately in an Effect is like plugging a power outlet into itself. The Effect runs, it sets the State, which causes a re-render, which causes the Effect to run, it sets the State again, this causes another re-render, and so on.
-Effects should usually synchronize your components with an *external* system. If there's no external system and you only want to adjust some state based on other state, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
+Effects should usually synchronize your components with an *external* system. If there's no external system and you only want to adjust some State based on other State, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
@@ -483,7 +483,7 @@ useEffect(() => {
}, []);
```
-**The code inside the Effect does not use any props or state, so your dependency array is `[]` (empty). This tells React to only run this code when the component "mounts", i.e. appears on the screen for the first time.**
+**The code inside the Effect does not use any props or State, so your dependency array is `[]` (empty). This tells React to only run this code when the component "mounts", i.e. appears on the screen for the first time.**
Let's try running this code:
@@ -653,7 +653,7 @@ useEffect(() => {
}, []);
```
-In development, opacity will be set to `1`, then to `0`, and then to `1` again. This should have the same user-visible behavior as setting it to `1` directly, which is what would happen in production. If you use a third-party animation library with support for tweening, your cleanup function should reset the timeline to its initial state.
+In development, opacity will be set to `1`, then to `0`, and then to `1` again. This should have the same user-visible behavior as setting it to `1` directly, which is what would happen in production. If you use a third-party animation library with support for tweening, your cleanup function should reset the timeline to its initial State.
### Fetching data {/*fetching-data*/}
@@ -680,7 +680,7 @@ useEffect(() => {
You can't "undo" a network request that already happened, but your cleanup function should ensure that the fetch that's _not relevant anymore_ does not keep affecting your application. If the `userId` changes from `'Alice'` to `'Bob'`, cleanup ensures that the `'Alice'` response is ignored even if it arrives after `'Bob'`.
-**In development, you will see two fetches in the Network tab.** There is nothing wrong with that. With the approach above, the first Effect will immediately get cleaned up so its copy of the `ignore` variable will be set to `true`. So even though there is an extra request, it won't affect the state thanks to the `if (!ignore)` check.
+**In development, you will see two fetches in the Network tab.** There is nothing wrong with that. With the approach above, the first Effect will immediately get cleaned up so its copy of the `ignore` variable will be set to `true`. So even though there is an extra request, it won't affect the State thanks to the `if (!ignore)` check.
**In production, there will only be one request.** If the second request in development is bothering you, the best approach is to use a solution that deduplicates requests and caches their responses between components:
@@ -698,7 +698,7 @@ This will not only improve the development experience, but also make your applic
Writing `fetch` calls inside Effects is a [popular way to fetch data](https://www.robinwieruch.de/react-hooks-fetch-data/), especially in fully client-side apps. This is, however, a very manual approach and it has significant downsides:
-- **Effects don't run on the server.** This means that the initial server-rendered HTML will only include a loading state with no data. The client computer will have to download all JavaScript and render your app only to discover that now it needs to load the data. This is not very efficient.
+- **Effects don't run on the server.** This means that the initial server-rendered HTML will only include a loading State with no data. The client computer will have to download all JavaScript and render your app only to discover that now it needs to load the data. This is not very efficient.
- **Fetching directly in Effects makes it easy to create "network waterfalls".** You render the parent component, it fetches some data, renders the child components, and then they start fetching their data. If the network is not very fast, this is significantly slower than fetching all data in parallel.
- **Fetching directly in Effects usually means you don't preload or cache data.** For example, if the component unmounts and then mounts again, it would have to fetch the data again.
- **It's not very ergonomic.** There's quite a bit of boilerplate code involved when writing `fetch` calls in a way that doesn't suffer from bugs like [race conditions.](https://maxrozen.com/race-conditions-fetching-data-react-with-useeffect)
@@ -835,7 +835,7 @@ Type something into the input and then immediately press "Unmount the component"
Finally, edit the component above and comment out the cleanup function so that the timeouts don't get cancelled. Try typing `abcde` fast. What do you expect to happen in three seconds? Will `console.log(text)` inside the timeout print the *latest* `text` and produce five `abcde` logs? Give it a try to check your intuition!
-Three seconds later, you should see a sequence of logs (`a`, `ab`, `abc`, `abcd`, and `abcde`) rather than five `abcde` logs. **Each Effect "captures" the `text` value from its corresponding render.** It doesn't matter that the `text` state changed: an Effect from the render with `text = 'ab'` will always see `'ab'`. In other words, Effects from each render are isolated from each other. If you're curious how this works, you can read about [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
+Three seconds later, you should see a sequence of logs (`a`, `ab`, `abc`, `abcd`, and `abcde`) rather than five `abcde` logs. **Each Effect "captures" the `text` value from its corresponding render.** It doesn't matter that the `text` State changed: an Effect from the render with `text = 'ab'` will always see `'ab'`. In other words, Effects from each render are isolated from each other. If you're curious how this works, you can read about [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
@@ -943,7 +943,7 @@ Finally, let's say the user navigates away, and the `ChatRoom` component unmount
#### Development-only behaviors {/*development-only-behaviors*/}
-When [Strict Mode](/reference/react/StrictMode) is on, React remounts every component once after mount (state and DOM are preserved). This [helps you find Effects that need cleanup](#step-3-add-cleanup-if-needed) and exposes bugs like race conditions early. Additionally, React will remount the Effects whenever you save a file in development. Both of these behaviors are development-only.
+When [Strict Mode](/reference/react/StrictMode) is on, React remounts every component once after mount (State and DOM are preserved). This [helps you find Effects that need cleanup](#step-3-add-cleanup-if-needed) and exposes bugs like race conditions early. Additionally, React will remount the Effects whenever you save a file in development. Both of these behaviors are development-only.
diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md
index 0f05a0569f6..b8823c986a5 100644
--- a/src/content/learn/thinking-in-react.md
+++ b/src/content/learn/thinking-in-react.md
@@ -75,7 +75,7 @@ Now that you've identified the components in the mockup, arrange them into a hie
Now that you have your component hierarchy, it's time to implement your app. The most straightforward approach is to build a version that renders the UI from your data model without adding any interactivity... yet! It's often easier to build the static version first and add interactivity later. Building a static version requires a lot of typing and no thinking, but adding interactivity requires a lot of thinking and not a lot of typing.
-To build a static version of your app that renders your data model, you'll want to build [components](/learn/your-first-component) that reuse other components and pass data using [props.](/learn/passing-props-to-a-component) Props are a way of passing data from parent to child. (If you're familiar with the concept of [state](/learn/state-a-components-memory), don't use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don't need it.)
+To build a static version of your app that renders your data model, you'll want to build [components](/learn/your-first-component) that reuse other components and pass data using [props.](/learn/passing-props-to-a-component) Props are a way of passing data from parent to child. (If you're familiar with the concept of [State](/learn/state-a-components-memory), don't use State at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don't need it.)
You can either build "top down" by starting with building the components higher up in the hierarchy (like `FilterableProductTable`) or "bottom up" by working from components lower down (like `ProductRow`). In simpler examples, it’s usually easier to go top-down, and on larger projects, it’s easier to go bottom-up.
@@ -201,15 +201,15 @@ After building your components, you'll have a library of reusable components tha
-At this point, you should not be using any state values. That’s for the next step!
+At this point, you should not be using any State values. That’s for the next step!
-## Step 3: Find the minimal but complete representation of UI state {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/}
+## Step 3: Find the minimal but complete representation of UI State {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/}
-To make the UI interactive, you need to let users change your underlying data model. You will use *state* for this.
+To make the UI interactive, you need to let users change your underlying data model. You will use *State* for this.
-Think of state as the minimal set of changing data that your app needs to remember. The most important principle for structuring state is to keep it [DRY (Don't Repeat Yourself).](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) Figure out the absolute minimal representation of the state your application needs and compute everything else on-demand. For example, if you're building a shopping list, you can store the items as an array in state. If you want to also display the number of items in the list, don't store the number of items as another state value--instead, read the length of your array.
+Think of State as the minimal set of changing data that your app needs to remember. The most important principle for structuring State is to keep it [DRY (Don't Repeat Yourself).](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) Figure out the absolute minimal representation of the State your application needs and compute everything else on-demand. For example, if you're building a shopping list, you can store the items as an array in State. If you want to also display the number of items in the list, don't store the number of items as another State value--instead, read the length of your array.
Now think of all of the pieces of data in this example application:
@@ -218,62 +218,62 @@ Now think of all of the pieces of data in this example application:
3. The value of the checkbox
4. The filtered list of products
-Which of these are state? Identify the ones that are not:
+Which of these are State? Identify the ones that are not:
-* Does it **remain unchanged** over time? If so, it isn't state.
-* Is it **passed in from a parent** via props? If so, it isn't state.
-* **Can you compute it** based on existing state or props in your component? If so, it *definitely* isn't state!
+* Does it **remain unchanged** over time? If so, it isn't State.
+* Is it **passed in from a parent** via props? If so, it isn't State.
+* **Can you compute it** based on existing State or props in your component? If so, it *definitely* isn't State!
-What's left is probably state.
+What's left is probably State.
Let's go through them one by one again:
-1. The original list of products is **passed in as props, so it's not state.**
-2. The search text seems to be state since it changes over time and can't be computed from anything.
-3. The value of the checkbox seems to be state since it changes over time and can't be computed from anything.
-4. The filtered list of products **isn't state because it can be computed** by taking the original list of products and filtering it according to the search text and value of the checkbox.
+1. The original list of products is **passed in as props, so it's not State.**
+2. The search text seems to be State since it changes over time and can't be computed from anything.
+3. The value of the checkbox seems to be State since it changes over time and can't be computed from anything.
+4. The filtered list of products **isn't State because it can be computed** by taking the original list of products and filtering it according to the search text and value of the checkbox.
-This means only the search text and the value of the checkbox are state! Nicely done!
+This means only the search text and the value of the checkbox are State! Nicely done!
#### Props vs State {/*props-vs-state*/}
-There are two types of "model" data in React: props and state. The two are very different:
+There are two types of "model" data in React: props and State. The two are very different:
* [**Props** are like arguments you pass](/learn/passing-props-to-a-component) to a function. They let a parent component pass data to a child component and customize its appearance. For example, a `Form` can pass a `color` prop to a `Button`.
-* [**State** is like a component’s memory.](/learn/state-a-components-memory) It lets a component keep track of some information and change it in response to interactions. For example, a `Button` might keep track of `isHovered` state.
+* [**State** is like a component’s memory.](/learn/state-a-components-memory) It lets a component keep track of some information and change it in response to interactions. For example, a `Button` might keep track of `isHovered` State.
Props and state are different, but they work together. A parent component will often keep some information in state (so that it can change it), and *pass it down* to child components as their props. It's okay if the difference still feels fuzzy on the first read. It takes a bit of practice for it to really stick!
-## Step 4: Identify where your state should live {/*step-4-identify-where-your-state-should-live*/}
+## Step 4: Identify where your State should live {/*step-4-identify-where-your-state-should-live*/}
-After identifying your app’s minimal state data, you need to identify which component is responsible for changing this state, or *owns* the state. Remember: React uses one-way data flow, passing data down the component hierarchy from parent to child component. It may not be immediately clear which component should own what state. This can be challenging if you’re new to this concept, but you can figure it out by following these steps!
+After identifying your app’s minimal State data, you need to identify which component is responsible for changing this State, or *owns* the State. Remember: React uses one-way data flow, passing data down the component hierarchy from parent to child component. It may not be immediately clear which component should own what State. This can be challenging if you’re new to this concept, but you can figure it out by following these steps!
-For each piece of state in your application:
+For each piece of State in your application:
-1. Identify *every* component that renders something based on that state.
+1. Identify *every* component that renders something based on that State.
2. Find their closest common parent component--a component above them all in the hierarchy.
-3. Decide where the state should live:
- 1. Often, you can put the state directly into their common parent.
- 2. You can also put the state into some component above their common parent.
- 3. If you can't find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common parent component.
+3. Decide where the State should live:
+ 1. Often, you can put the State directly into their common parent.
+ 2. You can also put the State into some component above their common parent.
+ 3. If you can't find a component where it makes sense to own the State, create a new component solely for holding the State and add it somewhere in the hierarchy above the common parent component.
-In the previous step, you found two pieces of state in this application: the search input text, and the value of the checkbox. In this example, they always appear together, so it makes sense to put them into the same place.
+In the previous step, you found two pieces of State in this application: the search input text, and the value of the checkbox. In this example, they always appear together, so it makes sense to put them into the same place.
Now let's run through our strategy for them:
-1. **Identify components that use state:**
- * `ProductTable` needs to filter the product list based on that state (search text and checkbox value).
- * `SearchBar` needs to display that state (search text and checkbox value).
+1. **Identify components that use State:**
+ * `ProductTable` needs to filter the product list based on that State (search text and checkbox value).
+ * `SearchBar` needs to display that State (search text and checkbox value).
1. **Find their common parent:** The first parent component both components share is `FilterableProductTable`.
-2. **Decide where the state lives**: We'll keep the filter text and checked state values in `FilterableProductTable`.
+2. **Decide where the State lives**: We'll keep the filter text and checked State values in `FilterableProductTable`.
-So the state values will live in `FilterableProductTable`.
+So the State values will live in `FilterableProductTable`.
-Add state to the component with the [`useState()` Hook.](/reference/react/useState) Hooks are special functions that let you "hook into" React. Add two state variables at the top of `FilterableProductTable` and specify their initial state:
+Add State to the component with the [`useState()` Hook.](/reference/react/useState) Hooks are special functions that let you "hook into" React. Add two State variables at the top of `FilterableProductTable` and specify their initial State:
```js
function FilterableProductTable({ products }) {
@@ -462,11 +462,11 @@ However, you haven't added any code to respond to the user actions like typing y
## Step 5: Add inverse data flow {/*step-5-add-inverse-data-flow*/}
-Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
+Currently your app renders correctly with props and State flowing down the hierarchy. But to change the State according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the State in `FilterableProductTable`.
-React makes this data flow explicit, but it requires a little more typing than two-way data binding. If you try to type or check the box in the example above, you'll see that React ignores your input. This is intentional. By writing ``, you've set the `value` prop of the `input` to always be equal to the `filterText` state passed in from `FilterableProductTable`. Since `filterText` state is never set, the input never changes.
+React makes this data flow explicit, but it requires a little more typing than two-way data binding. If you try to type or check the box in the example above, you'll see that React ignores your input. This is intentional. By writing ``, you've set the `value` prop of the `input` to always be equal to the `filterText` State passed in from `FilterableProductTable`. Since `filterText` State is never set, the input never changes.
-You want to make it so whenever the user changes the form inputs, the state updates to reflect those changes. The state is owned by `FilterableProductTable`, so only it can call `setFilterText` and `setInStockOnly`. To let `SearchBar` update the `FilterableProductTable`'s state, you need to pass these functions down to `SearchBar`:
+You want to make it so whenever the user changes the form inputs, the State updates to reflect those changes. The State is owned by `FilterableProductTable`, so only it can call `setFilterText` and `setInStockOnly`. To let `SearchBar` update the `FilterableProductTable`'s State, you need to pass these functions down to `SearchBar`:
```js {2,3,10,11}
function FilterableProductTable({ products }) {
@@ -482,7 +482,7 @@ function FilterableProductTable({ products }) {
onInStockOnlyChange={setInStockOnly} />
```
-Inside the `SearchBar`, you will add the `onChange` event handlers and set the parent state from them:
+Inside the `SearchBar`, you will add the `onChange` event handlers and set the parent State from them:
```js {4,5,13,19}
function SearchBar({
@@ -656,7 +656,7 @@ td {
-You can learn all about handling events and updating state in the [Adding Interactivity](/learn/adding-interactivity) section.
+You can learn all about handling events and updating State in the [Adding Interactivity](/learn/adding-interactivity) section.
## Where to go from here {/*where-to-go-from-here*/}
diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md
index d3779145685..e243eb386b5 100644
--- a/src/content/learn/tutorial-tic-tac-toe.md
+++ b/src/content/learn/tutorial-tic-tac-toe.md
@@ -17,7 +17,7 @@ This tutorial is designed for people who prefer to **learn by doing** and want t
The tutorial is divided into several sections:
- [Setup for the tutorial](#setup-for-the-tutorial) will give you **a starting point** to follow the tutorial.
-- [Overview](#overview) will teach you **the fundamentals** of React: components, props, and state.
+- [Overview](#overview) will teach you **the fundamentals** of React: components, props, and State.
- [Completing the game](#completing-the-game) will teach you **the most common techniques** in React development.
- [Adding time travel](#adding-time-travel) will give you **a deeper insight** into the unique strengths of React.
@@ -731,11 +731,11 @@ If you are following this tutorial using your local development environment, you
-As a next step, you want the Square component to "remember" that it got clicked, and fill it with an "X" mark. To "remember" things, components use *state*.
+As a next step, you want the Square component to "remember" that it got clicked, and fill it with an "X" mark. To "remember" things, components use *State*.
-React provides a special function called `useState` that you can call from your component to let it "remember" things. Let's store the current value of the `Square` in state, and change it when the `Square` is clicked.
+React provides a special function called `useState` that you can call from your component to let it "remember" things. Let's store the current value of the `Square` in State, and change it when the `Square` is clicked.
-Import `useState` at the top of the file. Remove the `value` prop from the `Square` component. Instead, add a new line at the start of the `Square` that calls `useState`. Have it return a state variable called `value`:
+Import `useState` at the top of the file. Remove the `value` prop from the `Square` component. Instead, add a new line at the start of the `Square` that calls `useState`. Have it return a State variable called `value`:
```js {1,3,4}
import { useState } from 'react';
@@ -747,7 +747,7 @@ function Square() {
//...
```
-`value` stores the value and `setValue` is a function that can be used to change the value. The `null` passed to `useState` is used as the initial value for this state variable, so `value` here starts off equal to `null`.
+`value` stores the value and `setValue` is a function that can be used to change the value. The `null` passed to `useState` is used as the initial value for this State variable, so `value` here starts off equal to `null`.
Since the `Square` component no longer accepts props anymore, you'll remove the `value` prop from all nine of the Square components created by the Board component:
@@ -801,7 +801,7 @@ By calling this `set` function from an `onClick` handler, you're telling React t

-Each Square has its own state: the `value` stored in each Square is completely independent of the others. When you call a `set` function in a component, React automatically updates the child components inside too.
+Each Square has its own State: the `value` stored in each Square is completely independent of the others. When you call a `set` function in a component, React automatically updates the child components inside too.
After you've made the above changes, your code will look like this:
@@ -899,7 +899,7 @@ body {
### React Developer Tools {/*react-developer-tools*/}
-React DevTools let you check the props and the state of your React components. You can find the React DevTools tab at the bottom of the _browser_ section in CodeSandbox:
+React DevTools let you check the props and the State of your React components. You can find the React DevTools tab at the bottom of the _browser_ section in CodeSandbox:

@@ -917,17 +917,17 @@ For local development, React DevTools is available as a [Chrome](https://chrome.
By this point, you have all the basic building blocks for your tic-tac-toe game. To have a complete game, you now need to alternate placing "X"s and "O"s on the board, and you need a way to determine a winner.
-### Lifting state up {/*lifting-state-up*/}
+### Lifting State up {/*lifting-state-up*/}
-Currently, each `Square` component maintains a part of the game's state. To check for a winner in a tic-tac-toe game, the `Board` would need to somehow know the state of each of the 9 `Square` components.
+Currently, each `Square` component maintains a part of the game's State. To check for a winner in a tic-tac-toe game, the `Board` would need to somehow know the State of each of the 9 `Square` components.
-How would you approach that? At first, you might guess that the `Board` needs to "ask" each `Square` for that `Square`'s state. Although this approach is technically possible in React, we discourage it because the code becomes difficult to understand, susceptible to bugs, and hard to refactor. Instead, the best approach is to store the game's state in the parent `Board` component instead of in each `Square`. The `Board` component can tell each `Square` what to display by passing a prop, like you did when you passed a number to each Square.
+How would you approach that? At first, you might guess that the `Board` needs to "ask" each `Square` for that `Square`'s State. Although this approach is technically possible in React, we discourage it because the code becomes difficult to understand, susceptible to bugs, and hard to refactor. Instead, the best approach is to store the game's State in the parent `Board` component instead of in each `Square`. The `Board` component can tell each `Square` what to display by passing a prop, like you did when you passed a number to each Square.
-**To collect data from multiple children, or to have two child components communicate with each other, declare the shared state in their parent component instead. The parent component can pass that state back down to the children via props. This keeps the child components in sync with each other and with their parent.**
+**To collect data from multiple children, or to have two child components communicate with each other, declare the shared State in their parent component instead. The parent component can pass that State back down to the children via props. This keeps the child components in sync with each other and with their parent.**
-Lifting state into a parent component is common when React components are refactored.
+Lifting State into a parent component is common when React components are refactored.
-Let's take this opportunity to try it out. Edit the `Board` component so that it declares a state variable named `squares` that defaults to an array of 9 nulls corresponding to the 9 squares:
+Let's take this opportunity to try it out. Edit the `Board` component so that it declares a State variable named `squares` that defaults to an array of 9 nulls corresponding to the 9 squares:
```js {3}
// ...
@@ -939,7 +939,7 @@ export default function Board() {
}
```
-`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The `useState()` call around it declares a `squares` state variable that's initially set to that array. Each entry in the array corresponds to the value of a square. When you fill the board in later, the `squares` array will look like this:
+`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The `useState()` call around it declares a `squares` State variable that's initially set to that array. Each entry in the array corresponds to the value of a square. When you fill the board in later, the `squares` array will look like this:
```jsx
['O', null, 'X', 'X', 'X', 'O', 'O', null, null]
@@ -1068,7 +1068,7 @@ body {
Each Square will now receive a `value` prop that will either be `'X'`, `'O'`, or `null` for empty squares.
-Next, you need to change what happens when a `Square` is clicked. The `Board` component now maintains which squares are filled. You'll need to create a way for the `Square` to update the `Board`'s state. Since state is private to a component that defines it, you cannot update the `Board`'s state directly from `Square`.
+Next, you need to change what happens when a `Square` is clicked. The `Board` component now maintains which squares are filled. You'll need to create a way for the `Square` to update the `Board`'s State. Since State is private to a component that defines it, you cannot update the `Board`'s State directly from `Square`.
Instead, you'll pass down a function from the `Board` component to the `Square` component, and you'll have `Square` call that function when a square is clicked. You'll start with the function that the `Square` component will call when it is clicked. You'll call that function `onSquareClick`:
@@ -1109,7 +1109,7 @@ export default function Board() {
}
```
-Lastly, you will define the `handleClick` function inside the Board component to update the `squares` array holding your board's state:
+Lastly, you will define the `handleClick` function inside the Board component to update the `squares` array holding your board's State:
```js {4-8}
export default function Board() {
@@ -1129,11 +1129,11 @@ export default function Board() {
The `handleClick` function creates a copy of the `squares` array (`nextSquares`) with the JavaScript `slice()` Array method. Then, `handleClick` updates the `nextSquares` array to add `X` to the first (`[0]` index) square.
-Calling the `setSquares` function lets React know the state of the component has changed. This will trigger a re-render of the components that use the `squares` state (`Board`) as well as its child components (the `Square` components that make up the board).
+Calling the `setSquares` function lets React know the State of the component has changed. This will trigger a re-render of the components that use the `squares` State (`Board`) as well as its child components (the `Square` components that make up the board).
-JavaScript supports [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) which means an inner function (e.g. `handleClick`) has access to variables and functions defined in a outer function (e.g. `Board`). The `handleClick` function can read the `squares` state and call the `setSquares` method because they are both defined inside of the `Board` function.
+JavaScript supports [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) which means an inner function (e.g. `handleClick`) has access to variables and functions defined in a outer function (e.g. `Board`). The `handleClick` function can read the `squares` State and call the `setSquares` method because they are both defined inside of the `Board` function.
@@ -1161,7 +1161,7 @@ Next, you will need to pass that `i` to `handleClick`. You could try to set the
```
-Here is why this doesn't work. The `handleClick(0)` call will be a part of rendering the board component. Because `handleClick(0)` alters the state of the board component by calling `setSquares`, your entire board component will be re-rendered again. But this runs `handleClick(0)` again, leading to an infinite loop:
+Here is why this doesn't work. The `handleClick(0)` call will be a part of rendering the board component. Because `handleClick(0)` alters the State of the board component by calling `setSquares`, your entire board component will be re-rendered again. But this runs `handleClick(0)` again, leading to an infinite loop:
@@ -1222,7 +1222,7 @@ Now you can again add X's to any square on the board by clicking on them:

-But this time all the state management is handled by the `Board` component!
+But this time all the State management is handled by the `Board` component!
This is what your code should look like:
@@ -1317,13 +1317,13 @@ body {
-Now that your state handling is in the `Board` component, the parent `Board` component passes props to the child `Square` components so that they can be displayed correctly. When clicking on a `Square`, the child `Square` component now asks the parent `Board` component to update the state of the board. When the `Board`'s state changes, both the `Board` component and every child `Square` re-renders automatically. Keeping the state of all squares in the `Board` component will allow it to determine the winner in the future.
+Now that your State handling is in the `Board` component, the parent `Board` component passes props to the child `Square` components so that they can be displayed correctly. When clicking on a `Square`, the child `Square` component now asks the parent `Board` component to update the State of the board. When the `Board`'s State changes, both the `Board` component and every child `Square` re-renders automatically. Keeping the State of all squares in the `Board` component will allow it to determine the winner in the future.
Let's recap what happens when a user clicks the top left square on your board to add an `X` to it:
1. Clicking on the upper left square runs the function that the `button` received as its `onClick` prop from the `Square`. The `Square` component received that function as its `onSquareClick` prop from the `Board`. The `Board` component defined that function directly in the JSX. It calls `handleClick` with an argument of `0`.
1. `handleClick` uses the argument (`0`) to update the first element of the `squares` array from `null` to `X`.
-1. The `squares` state of the `Board` component was updated, so the `Board` and all of its children re-render. This causes the `value` prop of the `Square` component with index `0` to change from `null` to `X`.
+1. The `squares` State of the `Board` component was updated, so the `Board` and all of its children re-render. This causes the `value` prop of the `Square` component with index `0` to change from `null` to `X`.
In the end the user sees that the upper left square has changed from empty to having a `X` after clicking it.
@@ -1357,13 +1357,13 @@ The result is the same but by not mutating (changing the underlying data) direct
Immutability makes complex features much easier to implement. Later in this tutorial, you will implement a "time travel" feature that lets you review the game's history and "jump back" to past moves. This functionality isn't specific to games--an ability to undo and redo certain actions is a common requirement for apps. Avoiding direct data mutation lets you keep previous versions of the data intact, and reuse them later.
-There is also another benefit of immutability. By default, all child components re-render automatically when the state of a parent component changes. This includes even the child components that weren't affected by the change. Although re-rendering is not by itself noticeable to the user (you shouldn't actively try to avoid it!), you might want to skip re-rendering a part of the tree that clearly wasn't affected by it for performance reasons. Immutability makes it very cheap for components to compare whether their data has changed or not. You can learn more about how React chooses when to re-render a component in [the `memo` API reference](/reference/react/memo).
+There is also another benefit of immutability. By default, all child components re-render automatically when the State of a parent component changes. This includes even the child components that weren't affected by the change. Although re-rendering is not by itself noticeable to the user (you shouldn't actively try to avoid it!), you might want to skip re-rendering a part of the tree that clearly wasn't affected by it for performance reasons. Immutability makes it very cheap for components to compare whether their data has changed or not. You can learn more about how React chooses when to re-render a component in [the `memo` API reference](/reference/react/memo).
### Taking turns {/*taking-turns*/}
It's now time to fix a major defect in this tic-tac-toe game: the "O"s cannot be marked on the board.
-You'll set the first move to be "X" by default. Let's keep track of this by adding another piece of state to the Board component:
+You'll set the first move to be "X" by default. Let's keep track of this by adding another piece of State to the Board component:
```js {2}
function Board() {
@@ -1374,7 +1374,7 @@ function Board() {
}
```
-Each time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next and the game's state will be saved. You'll update the `Board`'s `handleClick` function to flip the value of `xIsNext`:
+Each time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next and the game's State will be saved. You'll update the `Board`'s `handleClick` function to flip the value of `xIsNext`:
```js {7,8,9,10,11,13}
export default function Board() {
@@ -1406,7 +1406,7 @@ But wait, there's a problem. Try clicking on the same square multiple times:
The `X` is overwritten by an `O`! While this would add a very interesting twist to the game, we're going to stick to the original rules for now.
-When you mark a square with a `X` or an `O` you aren't first checking to see if the square already has a `X` or `O` value. You can fix this by *returning early*. You'll check to see if the square already has a `X` or an `O`. If the square is already filled, you will `return` in the `handleClick` function early--before it tries to update the board state.
+When you mark a square with a `X` or an `O` you aren't first checking to see if the square already has a `X` or `O` value. You can fix this by *returning early*. You'll check to see if the square already has a `X` or an `O`. If the square is already filled, you will `return` in the `handleClick` function early--before it tries to update the board State.
```js {2,3,4}
function handleClick(i) {
@@ -1731,7 +1731,7 @@ If you mutated the `squares` array, implementing time travel would be very diffi
However, you used `slice()` to create a new copy of the `squares` array after every move, and treated it as immutable. This will allow you to store every past version of the `squares` array, and navigate between the turns that have already happened.
-You'll store the past `squares` arrays in another array called `history`, which you'll store as a new state variable. The `history` array represents all board states, from the first to the last move, and has a shape like this:
+You'll store the past `squares` arrays in another array called `history`, which you'll store as a new State variable. The `history` array represents all board States, from the first to the last move, and has a shape like this:
```jsx
[
@@ -1745,11 +1745,11 @@ You'll store the past `squares` arrays in another array called `history`, which
]
```
-### Lifting state up, again {/*lifting-state-up-again*/}
+### Lifting State up, again {/*lifting-state-up-again*/}
-You will now write a new top-level component called `Game` to display a list of past moves. That's where you will place the `history` state that contains the entire game history.
+You will now write a new top-level component called `Game` to display a list of past moves. That's where you will place the `history` State that contains the entire game history.
-Placing the `history` state into the `Game` component will let you remove the `squares` state from its child `Board` component. Just like you "lifted state up" from the `Square` component into the `Board` component, you will now lift it up from the `Board` into the top-level `Game` component. This gives the `Game` component full control over the `Board`'s data and lets it instruct the `Board` to render previous turns from the `history`.
+Placing the `history` State into the `Game` component will let you remove the `squares` State from its child `Board` component. Just like you "lifted State up" from the `Square` component into the `Board` component, you will now lift it up from the `Board` into the top-level `Game` component. This gives the `Game` component full control over the `Board`'s data and lets it instruct the `Board` to render previous turns from the `history`.
First, add a `Game` component with `export default`. Have it render the `Board` component and some markup:
@@ -1774,7 +1774,7 @@ export default function Game() {
Note that you are removing the `export default` keywords before the `function Board() {` declaration and adding them before the `function Game() {` declaration. This tells your `index.js` file to use the `Game` component as the top-level component instead of your `Board` component. The additional `div`s returned by the `Game` component are making room for the game information you'll add to the board later.
-Add some state to the `Game` component to track which player is next and the history of moves:
+Add some State to the `Game` component to track which player is next and the history of moves:
```js {2-3}
export default function Game() {
@@ -1851,7 +1851,7 @@ The `Board` component is fully controlled by the props passed to it by the `Game
What should `handlePlay` do when called? Remember that Board used to call `setSquares` with an updated array; now it passes the updated `squares` array to `onPlay`.
-The `handlePlay` function needs to update `Game`'s state to trigger a re-render, but you don't have a `setSquares` function that you can call any more--you're now using the `history` state variable to store this information. You'll want to update `history` by appending the updated `squares` array as a new history entry. You also want to toggle `xIsNext`, just as Board used to do:
+The `handlePlay` function needs to update `Game`'s State to trigger a re-render, but you don't have a `setSquares` function that you can call any more--you're now using the `history` State variable to store this information. You'll want to update `history` by appending the updated `squares` array as a new history entry. You also want to toggle `xIsNext`, just as Board used to do:
```js {4-5}
export default function Game() {
@@ -1868,7 +1868,7 @@ Here, `[...history, nextSquares]` creates a new array that contains all the item
For example, if `history` is `[[null,null,null], ["X",null,null]]` and `nextSquares` is `["X",null,"O"]`, then the new `[...history, nextSquares]` array will be `[[null,null,null], ["X",null,null], ["X",null,"O"]]`.
-At this point, you've moved the state to live in the `Game` component, and the UI should be fully working, just as it was before the refactor. Here is what the code should look like at this point:
+At this point, you've moved the State to live in the `Game` component, and the UI should be fully working, just as it was before the refactor. Here is what the code should look like at this point:
@@ -2023,7 +2023,7 @@ Since you are recording the tic-tac-toe game's history, you can now display a li
React elements like `` are regular JavaScript objects; you can pass them around in your application. To render multiple items in React, you can use an array of React elements.
-You already have an array of `history` moves in state, so now you need to transform it to an array of React elements. In JavaScript, to transform one array into another, you can use the [array `map` method:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
+You already have an array of `history` moves in State, so now you need to transform it to an array of React elements. In JavaScript, to transform one array into another, you can use the [array `map` method:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
```jsx
[1, 2, 3].map((x) => x * 2) // [2, 4, 6]
@@ -2282,7 +2282,7 @@ In addition to the updated counts, a human reading this would probably say that
When a list is re-rendered, React takes each list item's key and searches the previous list's items for a matching key. If the current list has a key that didn't exist before, React creates a component. If the current list is missing a key that existed in the previous list, React destroys the previous component. If two keys match, the corresponding component is moved.
-Keys tell React about the identity of each component, which allows React to maintain state between re-renders. If a component's key changes, the component will be destroyed and re-created with a new state.
+Keys tell React about the identity of each component, which allows React to maintain State between re-renders. If a component's key changes, the component will be destroyed and re-created with a new State.
`key` is a special and reserved property in React. When an element is created, React extracts the `key` property and stores the key directly on the returned element. Even though `key` may look like it is passed as props, React automatically uses `key` to decide which components to update. There's no way for a component to ask what `key` its parent specified.
@@ -2476,7 +2476,7 @@ body {
-Before you can implement `jumpTo`, you need the `Game` component to keep track of which step the user is currently viewing. To do this, define a new state variable called `currentMove`, defaulting to `0`:
+Before you can implement `jumpTo`, you need the `Game` component to keep track of which step the user is currently viewing. To do this, define a new State variable called `currentMove`, defaulting to `0`:
```js {4}
export default function Game() {
@@ -2703,7 +2703,7 @@ body {
If you look at the code very closely, you may notice that `xIsNext === true` when `currentMove` is even and `xIsNext === false` when `currentMove` is odd. In other words, if you know the value of `currentMove`, then you can always figure out what `xIsNext` should be.
-There's no reason for you to store both of these in state. In fact, always try to avoid redundant state. Simplifying what you store in state reduces bugs and makes your code easier to understand. Change `Game` so that it doesn't store `xIsNext` as a separate state variable and instead figures it out based on the `currentMove`:
+There's no reason for you to store both of these in State. In fact, always try to avoid redundant State. Simplifying what you store in State reduces bugs and makes your code easier to understand. Change `Game` so that it doesn't store `xIsNext` as a separate State variable and instead figures it out based on the `currentMove`:
```js {4,11,15}
export default function Game() {
@@ -2725,7 +2725,7 @@ export default function Game() {
}
```
-You no longer need the `xIsNext` state declaration or the calls to `setXIsNext`. Now, there's no chance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding the components.
+You no longer need the `xIsNext` State declaration or the calls to `setXIsNext`. Now, there's no chance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding the components.
### Wrapping up {/*wrapping-up*/}
@@ -2915,4 +2915,4 @@ If you have extra time or want to practice your new React skills, here are some
1. When someone wins, highlight the three squares that caused the win (and when no one wins, display a message about the result being a draw).
1. Display the location for each move in the format (row, col) in the move history list.
-Throughout this tutorial, you've touched on React concepts including elements, components, props, and state. Now that you've seen how these concepts work when building a game, check out [Thinking in React](/learn/thinking-in-react) to see how the same React concepts work when build an app's UI.
+Throughout this tutorial, you've touched on React concepts including elements, components, props, and State. Now that you've seen how these concepts work when building a game, check out [Thinking in React](/learn/thinking-in-react) to see how the same React concepts work when build an app's UI.
diff --git a/src/content/learn/typescript.md b/src/content/learn/typescript.md
index 6f49c76567c..675a4c4a88a 100644
--- a/src/content/learn/typescript.md
+++ b/src/content/learn/typescript.md
@@ -130,14 +130,14 @@ However, we can look at a few examples of how to provide types for Hooks.
### `useState` {/*typing-usestate*/}
-The [`useState` Hook](/reference/react/useState) will re-use the value passed in as the initial state to determine what the type of the value should be. For example:
+The [`useState` Hook](/reference/react/useState) will re-use the value passed in as the initial State to determine what the type of the value should be. For example:
```ts
// Infer the type as "boolean"
const [enabled, setEnabled] = useState(false);
```
-Will assign the type of `boolean` to `enabled`, and `setEnabled` will be a function accepting either a `boolean` argument, or a function that returns a `boolean`. If you want to explicitly provide a type for the state, you can do so by providing a type argument to the `useState` call:
+Will assign the type of `boolean` to `enabled`, and `setEnabled` will be a function accepting either a `boolean` argument, or a function that returns a `boolean`. If you want to explicitly provide a type for the State, you can do so by providing a type argument to the `useState` call:
```ts
// Explicitly set the type to "boolean"
@@ -152,7 +152,7 @@ type Status = "idle" | "loading" | "success" | "error";
const [status, setStatus] = useState("idle");
```
-Or, as recommended in [Principles for structuring state](/learn/choosing-the-state-structure#principles-for-structuring-state), you can group related state as an object and describe the different possibilities via object types:
+Or, as recommended in [Principles for structuring State](/learn/choosing-the-state-structure#principles-for-structuring-state), you can group related State as an object and describe the different possibilities via object types:
```ts
type RequestState =
@@ -166,7 +166,7 @@ const [requestState, setRequestState] = useState({ status: 'idle'
### `useReducer` {/*typing-usereducer*/}
-The [`useReducer` Hook](/reference/react/useReducer) is a more complex Hook that takes a reducer function and an initial state. The types for the reducer function are inferred from the initial state. You can optionally provide a type argument to the `useReducer` call to provide a type for the state, but it is often better to set the type on the initial state instead:
+The [`useReducer` Hook](/reference/react/useReducer) is a more complex Hook that takes a reducer function and an initial State. The types for the reducer function are inferred from the initial State. You can optionally provide a type argument to the `useReducer` call to provide a type for the State, but it is often better to set the type on the initial State instead:
@@ -223,9 +223,9 @@ export default App = AppTSX;
We are using TypeScript in a few key places:
- - `interface State` describes the shape of the reducer's state.
+ - `interface State` describes the shape of the reducer's State.
- `type CounterAction` describes the different actions which can be dispatched to the reducer.
- - `const initialState: State` provides a type for the initial state, and also the type which is used by `useReducer` by default.
+ - `const initialState: State` provides a type for the initial State, and also the type which is used by `useReducer` by default.
- `stateReducer(state: State, action: CounterAction): State` sets the types for the reducer function's arguments and return value.
A more explicit alternative to setting the type on `initialState` is to provide a type argument to `useReducer`:
diff --git a/src/content/learn/updating-arrays-in-state.md b/src/content/learn/updating-arrays-in-state.md
index 61e4f4e2d98..ef8a76a1fd6 100644
--- a/src/content/learn/updating-arrays-in-state.md
+++ b/src/content/learn/updating-arrays-in-state.md
@@ -4,13 +4,13 @@ title: Updating Arrays in State
-Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.
+Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in State. Just like with objects, when you want to update an array stored in State, you need to create a new one (or make a copy of an existing one), and then set State to use the new array.
-- 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.
+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) |
| --------- | ----------------------------------- | ------------------------------------------------------------------- |
@@ -40,7 +40,7 @@ Unfortunately, [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript
* `slice` lets you copy an array or a part of it.
* `splice` **mutates** the array (to insert or delete items).
-In React, you will be using `slice` (no `p`!) a lot more often because you don't want to mutate objects or arrays in state. [Updating Objects](/learn/updating-objects-in-state) explains what mutation is and why it's not recommended for state.
+In React, you will be using `slice` (no `p`!) a lot more often because you don't want to mutate objects or arrays in State. [Updating Objects](/learn/updating-objects-in-state) explains what mutation is and why it's not recommended for State.
@@ -443,7 +443,7 @@ export default function List() {
Here, you use the `[...list]` spread syntax to create a copy of the original array first. Now that you have a copy, you can use mutating methods like `nextList.reverse()` or `nextList.sort()`, or even assign individual items with `nextList[0] = "something"`.
-However, **even if you copy an array, you can't mutate existing items _inside_ of it directly.** This is because copying is shallow--the new array will contain the same items as the original one. So if you modify an object inside the copied array, you are mutating the existing state. For example, code like this is a problem.
+However, **even if you copy an array, you can't mutate existing items _inside_ of it directly.** This is because copying is shallow--the new array will contain the same items as the original one. So if you modify an object inside the copied array, you are mutating the existing State. For example, code like this is a problem.
```js
const nextList = [...list];
@@ -451,15 +451,15 @@ nextList[0].seen = true; // Problem: mutates list[0]
setList(nextList);
```
-Although `nextList` and `list` are two different arrays, **`nextList[0]` and `list[0]` point to the same object.** So by changing `nextList[0].seen`, you are also changing `list[0].seen`. This is a state mutation, which you should avoid! You can solve this issue in a similar way to [updating nested JavaScript objects](/learn/updating-objects-in-state#updating-a-nested-object)--by copying individual items you want to change instead of mutating them. Here's how.
+Although `nextList` and `list` are two different arrays, **`nextList[0]` and `list[0]` point to the same object.** So by changing `nextList[0].seen`, you are also changing `list[0].seen`. This is a State mutation, which you should avoid! You can solve this issue in a similar way to [updating nested JavaScript objects](/learn/updating-objects-in-state#updating-a-nested-object)--by copying individual items you want to change instead of mutating them. Here's how.
## Updating objects inside arrays {/*updating-objects-inside-arrays*/}
Objects are not _really_ located "inside" arrays. They might appear to be "inside" in code, but each object in an array is a separate value, to which the array "points". This is why you need to be careful when changing nested fields like `list[0]`. Another person's artwork list may point to the same element of the array!
-**When updating nested state, you need to create copies from the point where you want to update, and all the way up to the top level.** Let's see how this works.
+**When updating nested State, you need to create copies from the point where you want to update, and all the way up to the top level.** Let's see how this works.
-In this example, two separate artwork lists have the same initial state. They are supposed to be isolated, but because of a mutation, their state is accidentally shared, and checking a box in one list affects the other list:
+In this example, two separate artwork lists have the same initial State. They are supposed to be isolated, but because of a mutation, their State is accidentally shared, and checking a box in one list affects the other list:
@@ -548,7 +548,7 @@ artwork.seen = nextSeen; // Problem: mutates an existing item
setMyList(myNextList);
```
-Although the `myNextList` array itself is new, the *items themselves* are the same as in the original `myList` array. So changing `artwork.seen` changes the *original* artwork item. That artwork item is also in `yourList`, which causes the bug. Bugs like this can be difficult to think about, but thankfully they disappear if you avoid mutating state.
+Although the `myNextList` array itself is new, the *items themselves* are the same as in the original `myList` array. So changing `artwork.seen` changes the *original* artwork item. That artwork item is also in `yourList`, which causes the bug. Bugs like this can be difficult to think about, but thankfully they disappear if you avoid mutating State.
**You can use `map` to substitute an old item with its updated version without mutation.**
@@ -566,7 +566,7 @@ setMyList(myList.map(artwork => {
Here, `...` is the object spread syntax used to [create a copy of an object.](/learn/updating-objects-in-state#copying-objects-with-the-spread-syntax)
-With this approach, none of the existing state items are being mutated, and the bug is fixed:
+With this approach, none of the existing State items are being mutated, and the bug is fixed:
@@ -652,7 +652,7 @@ function ItemList({ artworks, onToggle }) {
-In general, **you should only mutate objects that you have just created.** If you were inserting a *new* artwork, you could mutate it, but if you're dealing with something that's already in state, you need to make a copy.
+In general, **you should only mutate objects that you have just created.** If you were inserting a *new* artwork, you could mutate it, but if you're dealing with something that's already in State, you need to make a copy.
### Write concise update logic with Immer {/*write-concise-update-logic-with-immer*/}
@@ -773,12 +773,12 @@ updateMyTodos(draft => {
This is because you're not mutating the _original_ state, but you're mutating a special `draft` object provided by Immer. Similarly, you can apply mutating methods like `push()` and `pop()` to the content of the `draft`.
-Behind the scenes, Immer always constructs the next state from scratch according to the changes that you've done to the `draft`. This keeps your event handlers very concise without ever mutating state.
+Behind the scenes, Immer always constructs the next State from scratch according to the changes that you've done to the `draft`. This keeps your event handlers very concise without ever mutating State.
-- You can put arrays into state, but you can't change them.
-- Instead of mutating an array, create a *new* version of it, and update the state to it.
+- You can put arrays into State, but you can't change them.
+- Instead of mutating an array, create a *new* version of it, and update the State to it.
- You can use the `[...arr, newItem]` array spread syntax to create arrays with new items.
- You can use `filter()` and `map()` to create new arrays with filtered or transformed items.
- You can use Immer to keep your code concise.
@@ -1412,7 +1412,7 @@ ul, li { margin: 0; padding: 0; }
#### Fix the mutations using Immer {/*fix-the-mutations-using-immer*/}
-This is the same example as in the previous challenge. This time, fix the mutations by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `todos` state variable to use it.
+This is the same example as in the previous challenge. This time, fix the mutations by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `todos` State variable to use it.
diff --git a/src/content/learn/updating-objects-in-state.md b/src/content/learn/updating-objects-in-state.md
index 923e4e181f9..28c257897f4 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
@@ -19,7 +19,7 @@ State can hold any kind of JavaScript value, including objects. But you shouldn'
## What's a mutation? {/*whats-a-mutation*/}
-You can store any kind of JavaScript value in state.
+You can store any kind of JavaScript value in State.
```js
const [x, setX] = useState(0);
@@ -31,9 +31,9 @@ So far you've been working with numbers, strings, and booleans. These kinds of J
setX(5);
```
-The `x` state changed from `0` to `5`, but the _number `0` itself_ did not change. It's not possible to make any changes to the built-in primitive values like numbers, strings, and booleans in JavaScript.
+The `x` State changed from `0` to `5`, but the _number `0` itself_ did not change. It's not possible to make any changes to the built-in primitive values like numbers, strings, and booleans in JavaScript.
-Now consider an object in state:
+Now consider an object in State:
```js
const [position, setPosition] = useState({ x: 0, y: 0 });
@@ -45,13 +45,13 @@ 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*/}
+## Treat State as read-only {/*treat-state-as-read-only*/}
-In other words, you should **treat any JavaScript object that you put into state as read-only.**
+In other words, you should **treat any JavaScript object that you put into State as read-only.**
-This example holds an object in state to represent the current pointer position. The red dot is supposed to move when you touch or move the cursor over the preview area. But the dot stays in the initial position:
+This example holds an object in State to represent the current pointer position. The red dot is supposed to move when you touch or move the cursor over the preview area. But the dot stays in the initial position:
@@ -103,9 +103,9 @@ onPointerMove={e => {
}}
```
-This code modifies the object assigned to `position` from [the previous render.](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time) But without using the state setting function, React has no idea that object has changed. So React does not do anything in response. It's like trying to change the order after you've already eaten the meal. While mutating state can work in some cases, we don't recommend it. You should treat the state value you have access to in a render as read-only.
+This code modifies the object assigned to `position` from [the previous render.](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time) But without using the State setting function, React has no idea that object has changed. So React does not do anything in response. It's like trying to change the order after you've already eaten the meal. While mutating State can work in some cases, we don't recommend it. You should treat the State value you have access to in a render as read-only.
-To actually [trigger a re-render](/learn/state-as-a-snapshot#setting-state-triggers-renders) in this case, **create a *new* object and pass it to the state setting function:**
+To actually [trigger a re-render](/learn/state-as-a-snapshot#setting-state-triggers-renders) in this case, **create a *new* object and pass it to the State setting function:**
```js
onPointerMove={e => {
@@ -170,7 +170,7 @@ body { margin: 0; padding: 0; height: 250px; }
#### Local mutation is fine {/*local-mutation-is-fine*/}
-Code like this is a problem because it modifies an *existing* object in state:
+Code like this is a problem because it modifies an *existing* object in State:
```js
position.x = e.clientX;
@@ -195,7 +195,7 @@ setPosition({
});
```
-Mutation is only a problem when you change *existing* objects that are already in state. Mutating an object you've just created is okay because *no other code references it yet.* Changing it isn't going to accidentally impact something that depends on it. This is called a "local mutation". You can even do local mutation [while rendering.](/learn/keeping-components-pure#local-mutation-your-components-little-secret) Very convenient and completely okay!
+Mutation is only a problem when you change *existing* objects that are already in State. Mutating an object you've just created is okay because *no other code references it yet.* Changing it isn't going to accidentally impact something that depends on it. This is called a "local mutation". You can even do local mutation [while rendering.](/learn/keeping-components-pure#local-mutation-your-components-little-secret) Very convenient and completely okay!
@@ -203,7 +203,7 @@ Mutation is only a problem when you change *existing* objects that are already i
In the previous example, the `position` object is always created fresh from the current cursor position. But often, you will want to include *existing* data as a part of the new object you're creating. For example, you may want to update *only one* field in a form, but keep the previous values for all other fields.
-These input fields don't work because the `onChange` handlers mutate the state:
+These input fields don't work because the `onChange` handlers mutate the State:
@@ -269,7 +269,7 @@ input { margin-left: 5px; margin-bottom: 5px; }
-For example, this line mutates the state from a past render:
+For example, this line mutates the State from a past render:
```js
person.firstName = e.target.value;
@@ -296,7 +296,7 @@ setPerson({
Now the form works!
-Notice how you didn't declare a separate state variable for each input field. For large forms, keeping all data grouped in an object is very convenient--as long as you update it correctly!
+Notice how you didn't declare a separate State variable for each input field. For large forms, keeping all data grouped in an object is very convenient--as long as you update it correctly!
@@ -466,7 +466,7 @@ If you wanted to update `person.artwork.city`, it's clear how to do it with muta
person.artwork.city = 'New Delhi';
```
-But in React, you treat state as immutable! In order to change `city`, you would first need to produce the new `artwork` object (pre-populated with data from the previous one), and then produce the new `person` object which points at the new `artwork`:
+But in React, you treat State as immutable! In order to change `city`, you would first need to produce the new `artwork` object (pre-populated with data from the previous one), and then produce the new `person` object which points at the new `artwork`:
```js
const nextArtwork = { ...person.artwork, city: 'New Delhi' };
@@ -652,7 +652,7 @@ If you were to mutate `obj3.artwork.city`, it would affect both `obj2.artwork.ci
### Write concise update logic with Immer {/*write-concise-update-logic-with-immer*/}
-If your state is deeply nested, you might want to consider [flattening it.](/learn/choosing-the-state-structure#avoid-deeply-nested-state) But, if you don't want to change your state structure, you might prefer a shortcut to nested spreads. [Immer](https://github.com/immerjs/use-immer) is a popular library that lets you write using the convenient but mutating syntax and takes care of producing the copies for you. With Immer, the code you write looks like you are "breaking the rules" and mutating an object:
+If your State is deeply nested, you might want to consider [flattening it.](/learn/choosing-the-state-structure#avoid-deeply-nested-state) But, if you don't want to change your State structure, you might prefer a shortcut to nested spreads. [Immer](https://github.com/immerjs/use-immer) is a popular library that lets you write using the convenient but mutating syntax and takes care of producing the copies for you. With Immer, the code you write looks like you are "breaking the rules" and mutating an object:
```js
updatePerson(draft => {
@@ -660,7 +660,7 @@ updatePerson(draft => {
});
```
-But unlike a regular mutation, it doesn't overwrite the past state!
+But unlike a regular mutation, it doesn't overwrite the past State!
@@ -788,29 +788,29 @@ img { width: 200px; height: 200px; }
-Notice how much more concise the event handlers have become. You can mix and match `useState` and `useImmer` in a single component as much as you like. Immer is a great way to keep the update handlers concise, especially if there's nesting in your state, and copying objects leads to repetitive code.
+Notice how much more concise the event handlers have become. You can mix and match `useState` and `useImmer` in a single component as much as you like. Immer is a great way to keep the update handlers concise, especially if there's nesting in your State, and copying objects leads to repetitive code.
-#### Why is mutating state not recommended in React? {/*why-is-mutating-state-not-recommended-in-react*/}
+#### Why is mutating State not recommended in React? {/*why-is-mutating-state-not-recommended-in-react*/}
There are a few reasons:
-* **Debugging:** If you use `console.log` and don't mutate state, your past logs won't get clobbered by the more recent state changes. So you can clearly see how state has changed between renders.
-* **Optimizations:** Common React [optimization strategies](/reference/react/memo) rely on skipping work if previous props or state are the same as the next ones. If you never mutate state, it is very fast to check whether there were any changes. If `prevObj === obj`, you can be sure that nothing could have changed inside of it.
-* **New Features:** The new React features we're building rely on state being [treated like a snapshot.](/learn/state-as-a-snapshot) If you're mutating past versions of state, that may prevent you from using the new features.
-* **Requirement Changes:** Some application features, like implementing Undo/Redo, showing a history of changes, or letting the user reset a form to earlier values, are easier to do when nothing is mutated. This is because you can keep past copies of state in memory, and reuse them when appropriate. If you start with a mutative approach, features like this can be difficult to add later on.
-* **Simpler Implementation:** Because React does not rely on mutation, it does not need to do anything special with your objects. It does not need to hijack their properties, always wrap them into Proxies, or do other work at initialization as many "reactive" solutions do. This is also why React lets you put any object into state--no matter how large--without additional performance or correctness pitfalls.
+* **Debugging:** If you use `console.log` and don't mutate State, your past logs won't get clobbered by the more recent State changes. So you can clearly see how State has changed between renders.
+* **Optimizations:** Common React [optimization strategies](/reference/react/memo) rely on skipping work if previous props or State are the same as the next ones. If you never mutate State, it is very fast to check whether there were any changes. If `prevObj === obj`, you can be sure that nothing could have changed inside of it.
+* **New Features:** The new React features we're building rely on State being [treated like a snapshot.](/learn/state-as-a-snapshot) If you're mutating past versions of State, that may prevent you from using the new features.
+* **Requirement Changes:** Some application features, like implementing Undo/Redo, showing a history of changes, or letting the user reset a form to earlier values, are easier to do when nothing is mutated. This is because you can keep past copies of State in memory, and reuse them when appropriate. If you start with a mutative approach, features like this can be difficult to add later on.
+* **Simpler Implementation:** Because React does not rely on mutation, it does not need to do anything special with your objects. It does not need to hijack their properties, always wrap them into Proxies, or do other work at initialization as many "reactive" solutions do. This is also why React lets you put any object into State--no matter how large--without additional performance or correctness pitfalls.
-In practice, you can often "get away" with mutating state in React, but we strongly advise you not to do that so that you can use new React features developed with this approach in mind. Future contributors and perhaps even your future self will thank you!
+In practice, you can often "get away" with mutating State in React, but we strongly advise you not to do that so that you can use new React features developed with this approach in mind. Future contributors and perhaps even your future self will thank you!
-* Treat all state in React as immutable.
-* When you store objects in state, mutating them will not trigger renders and will change the state in previous render "snapshots".
-* Instead of mutating an object, create a *new* version of it, and trigger a re-render by setting state to it.
+* Treat all State in React as immutable.
+* When you store objects in State, mutating them will not trigger renders and will change the State in previous render "snapshots".
+* Instead of mutating an object, create a *new* version of it, and trigger a re-render by setting State to it.
* You can use the `{...obj, something: 'newValue'}` object spread syntax to create copies of objects.
* Spread syntax is shallow: it only copies one level deep.
* To update a nested object, you need to create copies all the way up from the place you're updating.
@@ -822,7 +822,7 @@ In practice, you can often "get away" with mutating state in React, but we stron
-#### Fix incorrect state updates {/*fix-incorrect-state-updates*/}
+#### Fix incorrect State updates {/*fix-incorrect-state-updates*/}
This form has a few bugs. Click the button that increases the score a few times. Notice that it does not increase. Then edit the first name, and notice that the score has suddenly "caught up" with your changes. Finally, edit the last name, and notice that the score has disappeared completely.
@@ -964,7 +964,7 @@ input { margin-left: 5px; margin-bottom: 5px; }
-The problem with `handlePlusClick` was that it mutated the `player` object. As a result, React did not know that there's a reason to re-render, and did not update the score on the screen. This is why, when you edited the first name, the state got updated, triggering a re-render which _also_ updated the score on the screen.
+The problem with `handlePlusClick` was that it mutated the `player` object. As a result, React did not know that there's a reason to re-render, and did not update the score on the screen. This is why, when you edited the first name, the State got updated, triggering a re-render which _also_ updated the score on the screen.
The problem with `handleLastNameChange` was that it did not copy the existing `...player` fields into the new object. This is why the score got lost after you edited the last name.
@@ -1287,7 +1287,7 @@ select { margin-bottom: 10px; }
#### Update an object with Immer {/*update-an-object-with-immer*/}
-This is the same buggy example as in the previous challenge. This time, fix the mutation by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `shape` state variable to use it.
+This is the same buggy example as in the previous challenge. This time, fix the mutation by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `shape` State variable to use it.
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 66cdc311775..edbb9f74370 100644
--- a/src/content/learn/you-might-not-need-an-effect.md
+++ b/src/content/learn/you-might-not-need-an-effect.md
@@ -4,7 +4,7 @@ title: 'You Might Not Need an Effect'
-Effects are an escape hatch from the React paradigm. They let you "step outside" of React and synchronize your components with some external system like a non-React widget, network, or the browser DOM. If there is no external system involved (for example, if you want to update a component's state when some props or state change), you shouldn't need an Effect. Removing unnecessary Effects will make your code easier to follow, faster to run, and less error-prone.
+Effects are an escape hatch from the React paradigm. They let you "step outside" of React and synchronize your components with some external system like a non-React widget, network, or the browser DOM. If there is no external system involved (for example, if you want to update a component's State when some props or State change), you shouldn't need an Effect. Removing unnecessary Effects will make your code easier to follow, faster to run, and less error-prone.
@@ -12,7 +12,7 @@ Effects are an escape hatch from the React paradigm. They let you "step outside"
* Why and how to remove unnecessary Effects from your components
* How to cache expensive computations without Effects
-* How to reset and adjust component state without Effects
+* How to reset and adjust component State without Effects
* How to share logic between event handlers
* Which logic should be moved to event handlers
* How to notify parent components about changes
@@ -23,16 +23,16 @@ Effects are an escape hatch from the React paradigm. They let you "step outside"
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 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/start-a-new-react-project#production-grade-react-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/start-a-new-react-project#production-grade-react-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!
-### Updating state based on props or state {/*updating-state-based-on-props-or-state*/}
+### Updating State based on props or State {/*updating-state-based-on-props-or-state*/}
-Suppose you have a component with two state variables: `firstName` and `lastName`. You want to calculate a `fullName` from them by concatenating them. Moreover, you'd like `fullName` to update whenever `firstName` or `lastName` change. Your first instinct might be to add a `fullName` state variable and update it in an Effect:
+Suppose you have a component with two State variables: `firstName` and `lastName`. You want to calculate a `fullName` from them by concatenating them. Moreover, you'd like `fullName` to update whenever `firstName` or `lastName` change. Your first instinct might be to add a `fullName` State variable and update it in an Effect:
```js {5-9}
function Form() {
@@ -48,7 +48,7 @@ function Form() {
}
```
-This is more complicated than necessary. It is inefficient too: it does an entire render pass with a stale value for `fullName`, then immediately re-renders with the updated value. Remove the state variable and the Effect:
+This is more complicated than necessary. It is inefficient too: it does an entire render pass with a stale value for `fullName`, then immediately re-renders with the updated value. Remove the State variable and the Effect:
```js {4-5}
function Form() {
@@ -60,7 +60,7 @@ function Form() {
}
```
-**When something can be calculated from the existing props or state, [don't put it in state.](/learn/choosing-the-state-structure#avoid-redundant-state) Instead, calculate it during rendering.** This makes your code faster (you avoid the extra "cascading" updates), simpler (you remove some code), and less error-prone (you avoid bugs caused by different state variables getting out of sync with each other). If this approach feels new to you, [Thinking in React](/learn/thinking-in-react#step-3-find-the-minimal-but-complete-representation-of-ui-state) explains what should go into state.
+**When something can be calculated from the existing props or State, [don't put it in State.](/learn/choosing-the-state-structure#avoid-redundant-state) Instead, calculate it during rendering.** This makes your code faster (you avoid the extra "cascading" updates), simpler (you remove some code), and less error-prone (you avoid bugs caused by different State variables getting out of sync with each other). If this approach feels new to you, [Thinking in React](/learn/thinking-in-react#step-3-find-the-minimal-but-complete-representation-of-ui-state) explains what should go into State.
### Caching expensive calculations {/*caching-expensive-calculations*/}
@@ -80,7 +80,7 @@ function TodoList({ todos, filter }) {
}
```
-Like in the earlier example, this is both unnecessary and inefficient. First, remove the state and the Effect:
+Like in the earlier example, this is both unnecessary and inefficient. First, remove the State and the Effect:
```js {3-4}
function TodoList({ todos, filter }) {
@@ -91,7 +91,7 @@ function TodoList({ todos, filter }) {
}
```
-Usually, this code is fine! But maybe `getFilteredTodos()` is slow or you have a lot of `todos`. In that case you don't want to recalculate `getFilteredTodos()` if some unrelated state variable like `newTodo` has changed.
+Usually, this code is fine! But maybe `getFilteredTodos()` is slow or you have a lot of `todos`. In that case you don't want to recalculate `getFilteredTodos()` if some unrelated State variable like `newTodo` has changed.
You can cache (or ["memoize"](https://en.wikipedia.org/wiki/Memoization)) an expensive calculation by wrapping it in a [`useMemo`](/reference/react/useMemo) Hook:
@@ -155,9 +155,9 @@ Also note that measuring performance in development will not give you the most a
-### Resetting all state when a prop changes {/*resetting-all-state-when-a-prop-changes*/}
+### Resetting all State when a prop changes {/*resetting-all-state-when-a-prop-changes*/}
-This `ProfilePage` component receives a `userId` prop. The page contains a comment input, and you use a `comment` state variable to hold its value. One day, you notice a problem: when you navigate from one profile to another, the `comment` state does not get reset. As a result, it's easy to accidentally post a comment on a wrong user's profile. To fix the issue, you want to clear out the `comment` state variable whenever the `userId` changes:
+This `ProfilePage` component receives a `userId` prop. The page contains a comment input, and you use a `comment` State variable to hold its value. One day, you notice a problem: when you navigate from one profile to another, the `comment` State does not get reset. As a result, it's easy to accidentally post a comment on a wrong user's profile. To fix the issue, you want to clear out the `comment` State variable whenever the `userId` changes:
```js {4-7}
export default function ProfilePage({ userId }) {
@@ -171,7 +171,7 @@ export default function ProfilePage({ userId }) {
}
```
-This is inefficient because `ProfilePage` and its children will first render with the stale value, and then render again. It is also complicated because you'd need to do this in *every* component that has some state inside `ProfilePage`. For example, if the comment UI is nested, you'd want to clear out nested comment state too.
+This is inefficient because `ProfilePage` and its children will first render with the stale value, and then render again. It is also complicated because you'd need to do this in *every* component that has some State inside `ProfilePage`. For example, if the comment UI is nested, you'd want to clear out nested comment State too.
Instead, you can tell React that each user's profile is conceptually a _different_ profile by giving it an explicit key. Split your component in two and pass a `key` attribute from the outer component to the inner one:
@@ -192,15 +192,15 @@ function Profile({ userId }) {
}
```
-Normally, React preserves the state when the same component is rendered in the same spot. **By passing `userId` as a `key` to the `Profile` component, you're asking React to treat two `Profile` components with different `userId` as two different components that should not share any state.** Whenever the key (which you've set to `userId`) changes, React will recreate the DOM and [reset the state](/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key) of the `Profile` component and all of its children. Now the `comment` field will clear out automatically when navigating between profiles.
+Normally, React preserves the State when the same component is rendered in the same spot. **By passing `userId` as a `key` to the `Profile` component, you're asking React to treat two `Profile` components with different `userId` as two different components that should not share any State.** Whenever the key (which you've set to `userId`) changes, React will recreate the DOM and [reset the State](/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key) of the `Profile` component and all of its children. Now the `comment` field will clear out automatically when navigating between profiles.
Note that in this example, only the outer `ProfilePage` component is exported and visible to other files in the project. Components rendering `ProfilePage` don't need to pass the key to it: they pass `userId` as a regular prop. The fact `ProfilePage` passes it as a `key` to the inner `Profile` component is an implementation detail.
-### Adjusting some state when a prop changes {/*adjusting-some-state-when-a-prop-changes*/}
+### Adjusting some State when a prop changes {/*adjusting-some-state-when-a-prop-changes*/}
-Sometimes, you might want to reset or adjust a part of the state on a prop change, but not all of it.
+Sometimes, you might want to reset or adjust a part of the State on a prop change, but not all of it.
-This `List` component receives a list of `items` as a prop, and maintains the selected item in the `selection` state variable. You want to reset the `selection` to `null` whenever the `items` prop receives a different array:
+This `List` component receives a list of `items` as a prop, and maintains the selected item in the `selection` State variable. You want to reset the `selection` to `null` whenever the `items` prop receives a different array:
```js {5-8}
function List({ items }) {
@@ -217,7 +217,7 @@ function List({ items }) {
This, too, is not ideal. Every time the `items` change, the `List` and its child components will render with a stale `selection` value at first. Then React will update the DOM and run the Effects. Finally, the `setSelection(null)` call will cause another re-render of the `List` and its child components, restarting this whole process again.
-Start by deleting the Effect. Instead, adjust the state directly during rendering:
+Start by deleting the Effect. Instead, adjust the State directly during rendering:
```js {5-11}
function List({ items }) {
@@ -234,11 +234,11 @@ function List({ items }) {
}
```
-[Storing information from previous renders](/reference/react/useState#storing-information-from-previous-renders) like this can be hard to understand, but it’s better than updating the same state in an Effect. In the above example, `setSelection` is called directly during a render. React will re-render the `List` *immediately* after it exits with a `return` statement. React has not rendered the `List` children or updated the DOM yet, so this lets the `List` children skip rendering the stale `selection` value.
+[Storing information from previous renders](/reference/react/useState#storing-information-from-previous-renders) like this can be hard to understand, but it’s better than updating the same State in an Effect. In the above example, `setSelection` is called directly during a render. React will re-render the `List` *immediately* after it exits with a `return` statement. React has not rendered the `List` children or updated the DOM yet, so this lets the `List` children skip rendering the stale `selection` value.
-When you update a component during rendering, React throws away the returned JSX and immediately retries rendering. To avoid very slow cascading retries, React only lets you update the *same* component's state during a render. If you update another component's state during a render, you'll see an error. A condition like `items !== prevItems` is necessary to avoid loops. You may adjust state like this, but any other side effects (like changing the DOM or setting timeouts) should stay in event handlers or Effects to [keep components pure.](/learn/keeping-components-pure)
+When you update a component during rendering, React throws away the returned JSX and immediately retries rendering. To avoid very slow cascading retries, React only lets you update the *same* component's State during a render. If you update another component's State during a render, you'll see an error. A condition like `items !== prevItems` is necessary to avoid loops. You may adjust State like this, but any other side effects (like changing the DOM or setting timeouts) should stay in event handlers or Effects to [keep components pure.](/learn/keeping-components-pure)
-**Although this pattern is more efficient than an Effect, most components shouldn't need it either.** No matter how you do it, adjusting state based on props or other state makes your data flow more difficult to understand and debug. Always check whether you can [reset all state with a key](#resetting-all-state-when-a-prop-changes) or [calculate everything during rendering](#updating-state-based-on-props-or-state) instead. For example, instead of storing (and resetting) the selected *item*, you can store the selected *item ID:*
+**Although this pattern is more efficient than an Effect, most components shouldn't need it either.** No matter how you do it, adjusting State based on props or other State makes your data flow more difficult to understand and debug. Always check whether you can [reset all State with a key](#resetting-all-state-when-a-prop-changes) or [calculate everything during rendering](#updating-state-based-on-props-or-state) instead. For example, instead of storing (and resetting) the selected *item*, you can store the selected *item ID:*
```js {3-5}
function List({ items }) {
@@ -250,7 +250,7 @@ function List({ items }) {
}
```
-Now there is no need to "adjust" the state at all. If the item with the selected ID is in the list, it remains selected. If it's not, the `selection` calculated during rendering will be `null` because no matching item was found. This behavior is different, but arguably better because most changes to `items` preserve the selection.
+Now there is no need to "adjust" the State at all. If the item with the selected ID is in the list, it remains selected. If it's not, the `selection` calculated during rendering will be `null` because no matching item was found. This behavior is different, but arguably better because most changes to `items` preserve the selection.
### Sharing logic between event handlers {/*sharing-logic-between-event-handlers*/}
@@ -362,7 +362,7 @@ When you choose whether to put some logic into an event handler or an Effect, th
### Chains of computations {/*chains-of-computations*/}
-Sometimes you might feel tempted to chain Effects that each adjust a piece of state based on other state:
+Sometimes you might feel tempted to chain Effects that each adjust a piece of State based on other State:
```js {7-29}
function Game() {
@@ -410,9 +410,9 @@ There are two problems with this code.
One problem is that it is very inefficient: the component (and its children) have to re-render between each `set` call in the chain. In the example above, in the worst case (`setCard` → render → `setGoldCardCount` → render → `setRound` → render → `setIsGameOver` → render) there are three unnecessary re-renders of the tree below.
-Even if it weren't slow, as your code evolves, you will run into cases where the "chain" you wrote doesn't fit the new requirements. Imagine you are adding a way to step through the history of the game moves. You'd do it by updating each state variable to a value from the past. However, setting the `card` state to a value from the past would trigger the Effect chain again and change the data you're showing. Such code is often rigid and fragile.
+Even if it weren't slow, as your code evolves, you will run into cases where the "chain" you wrote doesn't fit the new requirements. Imagine you are adding a way to step through the history of the game moves. You'd do it by updating each State variable to a value from the past. However, setting the `card` State to a value from the past would trigger the Effect chain again and change the data you're showing. Such code is often rigid and fragile.
-In this case, it's better to calculate what you can during rendering, and adjust the state in the event handler:
+In this case, it's better to calculate what you can during rendering, and adjust the State in the event handler:
```js {6-7,14-26}
function Game() {
@@ -446,11 +446,11 @@ function Game() {
// ...
```
-This is a lot more efficient. Also, if you implement a way to view game history, now you will be able to set each state variable to a move from the past without triggering the Effect chain that adjusts every other value. If you need to reuse logic between several event handlers, you can [extract a function](#sharing-logic-between-event-handlers) and call it from those handlers.
+This is a lot more efficient. Also, if you implement a way to view game history, now you will be able to set each State variable to a move from the past without triggering the Effect chain that adjusts every other value. If you need to reuse logic between several event handlers, you can [extract a function](#sharing-logic-between-event-handlers) and call it from those handlers.
-Remember that inside event handlers, [state behaves like a snapshot.](/learn/state-as-a-snapshot) For example, even after you call `setRound(round + 1)`, the `round` variable will reflect the value at the time the user clicked the button. If you need to use the next value for calculations, define it manually like `const nextRound = round + 1`.
+Remember that inside event handlers, [State behaves like a snapshot.](/learn/state-as-a-snapshot) For example, even after you call `setRound(round + 1)`, the `round` variable will reflect the value at the time the user clicked the button. If you need to use the next value for calculations, define it manually like `const nextRound = round + 1`.
-In some cases, you *can't* calculate the next state directly in the event handler. For example, imagine a form with multiple dropdowns where the options of the next dropdown depend on the selected value of the previous dropdown. Then, a chain of Effects is appropriate because you are synchronizing with network.
+In some cases, you *can't* calculate the next State directly in the event handler. For example, imagine a form with multiple dropdowns where the options of the next dropdown depend on the selected value of the previous dropdown. Then, a chain of Effects is appropriate because you are synchronizing with network.
### Initializing the application {/*initializing-the-application*/}
@@ -505,9 +505,9 @@ function App() {
Code at the top level runs once when your component is imported--even if it doesn't end up being rendered. To avoid slowdown or surprising behavior when importing arbitrary components, don't overuse this pattern. Keep app-wide initialization logic to root component modules like `App.js` or in your application's entry point.
-### Notifying parent components about state changes {/*notifying-parent-components-about-state-changes*/}
+### Notifying parent components about State changes {/*notifying-parent-components-about-state-changes*/}
-Let's say you're writing a `Toggle` component with an internal `isOn` state which can be either `true` or `false`. There are a few different ways to toggle it (by clicking or dragging). You want to notify the parent component whenever the `Toggle` internal state changes, so you expose an `onChange` event and call it from an Effect:
+Let's say you're writing a `Toggle` component with an internal `isOn` State which can be either `true` or `false`. There are a few different ways to toggle it (by clicking or dragging). You want to notify the parent component whenever the `Toggle` internal State changes, so you expose an `onChange` event and call it from an Effect:
```js {4-7}
function Toggle({ onChange }) {
@@ -534,9 +534,9 @@ function Toggle({ onChange }) {
}
```
-Like earlier, this is not ideal. The `Toggle` updates its state first, and React updates the screen. Then React runs the Effect, which calls the `onChange` function passed from a parent component. Now the parent component will update its own state, starting another render pass. It would be better to do everything in a single pass.
+Like earlier, this is not ideal. The `Toggle` updates its State first, and React updates the screen. Then React runs the Effect, which calls the `onChange` function passed from a parent component. Now the parent component will update its own State, starting another render pass. It would be better to do everything in a single pass.
-Delete the Effect and instead update the state of *both* components within the same event handler:
+Delete the Effect and instead update the State of *both* components within the same event handler:
```js {5-7,11,16,18}
function Toggle({ onChange }) {
@@ -564,9 +564,9 @@ function Toggle({ onChange }) {
}
```
-With this approach, both the `Toggle` component and its parent component update their state during the event. React [batches updates](/learn/queueing-a-series-of-state-updates) from different components together, so there will only be one render pass.
+With this approach, both the `Toggle` component and its parent component update their State during the event. React [batches updates](/learn/queueing-a-series-of-state-updates) from different components together, so there will only be one render pass.
-You might also be able to remove the state altogether, and instead receive `isOn` from the parent component:
+You might also be able to remove the State altogether, and instead receive `isOn` from the parent component:
```js {1,2}
// ✅ Also good: the component is fully controlled by its parent
@@ -587,7 +587,7 @@ function Toggle({ isOn, onChange }) {
}
```
-["Lifting state up"](/learn/sharing-state-between-components) lets the parent component fully control the `Toggle` by toggling the parent's own state. This means the parent component will have to contain more logic, but there will be less state overall to worry about. Whenever you try to keep two different state variables synchronized, try lifting state up instead!
+["Lifting state up"](/learn/sharing-state-between-components) lets the parent component fully control the `Toggle` by toggling the parent's own State. This means the parent component will have to contain more logic, but there will be less State overall to worry about. Whenever you try to keep two different State variables synchronized, try lifting State up instead!
### Passing data to the parent {/*passing-data-to-the-parent*/}
@@ -612,7 +612,7 @@ function Child({ onFetched }) {
}
```
-In React, data flows from the parent components to their children. When you see something wrong on the screen, you can trace where the information comes from by going up the component chain until you find which component passes the wrong prop or has the wrong state. When child components update the state of their parent components in Effects, the data flow becomes very difficult to trace. Since both the child and the parent need the same data, let the parent component fetch that data, and *pass it down* to the child instead:
+In React, data flows from the parent components to their children. When you see something wrong on the screen, you can trace where the information comes from by going up the component chain until you find which component passes the wrong prop or has the wrong State. When child components update the State of their parent components in Effects, the data flow becomes very difficult to trace. Since both the child and the parent need the same data, let the parent component fetch that data, and *pass it down* to the child instead:
```js {4-5}
function Parent() {
@@ -631,7 +631,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() {
@@ -660,7 +660,7 @@ function ChatIndicator() {
}
```
-Here, the component subscribes to an external data store (in this case, the browser `navigator.onLine` API). Since this API does not exist on the server (so it can't be used for the initial HTML), initially the state is set to `true`. Whenever the value of that data store changes in the browser, the component updates its state.
+Here, the component subscribes to an external data store (in this case, the browser `navigator.onLine` API). Since this API does not exist on the server (so it can't be used for the initial HTML), initially the State is set to `true`. Whenever the value of that data store changes in the browser, the component updates its State.
Although it's common to use Effects for this, React has a purpose-built Hook for subscribing to an external store that is preferred instead. Delete the Effect and replace it with a call to [`useSyncExternalStore`](/reference/react/useSyncExternalStore):
@@ -689,7 +689,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*/}
@@ -794,11 +794,11 @@ In general, whenever you have to resort to writing Effects, keep an eye out for
- If you can calculate something during render, you don't need an Effect.
- To cache expensive calculations, add `useMemo` instead of `useEffect`.
-- To reset the state of an entire component tree, pass a different `key` to it.
-- To reset a particular bit of state in response to a prop change, set it during rendering.
+- To reset the State of an entire component tree, pass a different `key` to it.
+- To reset a particular bit of State in response to a prop change, set it during rendering.
- Code that runs because a component was *displayed* should be in Effects, the rest should be in events.
-- If you need to update the state of several components, it's better to do it during a single event.
-- Whenever you try to synchronize state variables in different components, consider lifting state up.
+- If you need to update the State of several components, it's better to do it during a single event.
+- Whenever you try to synchronize State variables in different components, consider lifting State up.
- You can fetch data with Effects, but you need to implement cleanup to avoid race conditions.
@@ -809,7 +809,7 @@ In general, whenever you have to resort to writing Effects, keep an eye out for
The `TodoList` below displays a list of todos. When the "Show only active todos" checkbox is ticked, completed todos are not displayed in the list. Regardless of which todos are visible, the footer displays the count of todos that are not yet completed.
-Simplify this component by removing all the unnecessary state and Effects.
+Simplify this component by removing all the unnecessary State and Effects.
@@ -915,7 +915,7 @@ If you can calculate something during rendering, you don't need state or an Effe
-There are only two essential pieces of state in this example: the list of `todos` and the `showActive` state variable which represents whether the checkbox is ticked. All of the other state variables are [redundant](/learn/choosing-the-state-structure#avoid-redundant-state) and can be calculated during rendering instead. This includes the `footer` which you can move directly into the surrounding JSX.
+There are only two essential pieces of State in this example: the list of `todos` and the `showActive` State variable which represents whether the checkbox is ticked. All of the other State variables are [redundant](/learn/choosing-the-state-structure#avoid-redundant-state) and can be calculated during rendering instead. This includes the `footer` which you can move directly into the surrounding JSX.
Your result should end up looking like this:
@@ -1177,9 +1177,9 @@ input { margin-top: 10px; }
-With this change, `getVisibleTodos()` will be called only if `todos` or `showActive` change. Typing into the input only changes the `text` state variable, so it does not trigger a call to `getVisibleTodos()`.
+With this change, `getVisibleTodos()` will be called only if `todos` or `showActive` change. Typing into the input only changes the `text` State variable, so it does not trigger a call to `getVisibleTodos()`.
-There is also another solution which does not need `useMemo`. Since the `text` state variable can't possibly affect the list of todos, you can extract the `NewTodo` form into a separate component, and move the `text` state variable inside of it:
+There is also another solution which does not need `useMemo`. Since the `text` State variable can't possibly affect the list of todos, you can extract the `NewTodo` form into a separate component, and move the `text` State variable inside of it:
@@ -1266,11 +1266,11 @@ input { margin-top: 10px; }
-This approach satisfies the requirements too. When you type into the input, only the `text` state variable updates. Since the `text` state variable is in the child `NewTodo` component, the parent `TodoList` component won't get re-rendered. This is why `getVisibleTodos()` doesn't get called when you type. (It would still be called if the `TodoList` re-renders for another reason.)
+This approach satisfies the requirements too. When you type into the input, only the `text` State variable updates. Since the `text` State variable is in the child `NewTodo` component, the parent `TodoList` component won't get re-rendered. This is why `getVisibleTodos()` doesn't get called when you type. (It would still be called if the `TodoList` re-renders for another reason.)
-#### Reset state without Effects {/*reset-state-without-effects*/}
+#### Reset State without Effects {/*reset-state-without-effects*/}
This `EditContact` component receives a contact object shaped like `{ id, name, email }` as the `savedContact` prop. Try editing the name and email input fields. When you press Save, the contact's button above the form updates to the edited name. When you press Reset, any pending changes in the form are discarded. Play around with this UI to get a feel for it.
@@ -1432,13 +1432,13 @@ button {
-It would be nice if there was a way to tell React that when `savedContact.id` is different, the `EditContact` form is conceptually a _different contact's form_ and should not preserve state. Do you recall any such way?
+It would be nice if there was a way to tell React that when `savedContact.id` is different, the `EditContact` form is conceptually a _different contact's form_ and should not preserve State. Do you recall any such way?
-Split the `EditContact` component in two. Move all the form state into the inner `EditForm` component. Export the outer `EditContact` component, and make it pass `savedContact.id` as the `key` to the inner `EditForm` component. As a result, the inner `EditForm` component resets all of the form state and recreates the DOM whenever you select a different contact.
+Split the `EditContact` component in two. Move all the form State into the inner `EditForm` component. Export the outer `EditContact` component, and make it pass `savedContact.id` as the `key` to the inner `EditForm` component. As a result, the inner `EditForm` component resets all of the form State and recreates the DOM whenever you select a different contact.
@@ -1602,9 +1602,9 @@ button {
#### Submit a form without Effects {/*submit-a-form-without-effects*/}
-This `Form` component lets you send a message to a friend. When you submit the form, the `showForm` state variable is set to `false`. This triggers an Effect calling `sendMessage(message)`, which sends the message (you can see it in the console). After the message is sent, you see a "Thank you" dialog with an "Open chat" button that lets you get back to the form.
+This `Form` component lets you send a message to a friend. When you submit the form, the `showForm` State variable is set to `false`. This triggers an Effect calling `sendMessage(message)`, which sends the message (you can see it in the console). After the message is sent, you see a "Thank you" dialog with an "Open chat" button that lets you get back to the form.
-Your app's users are sending way too many messages. To make chatting a little bit more difficult, you've decided to show the "Thank you" dialog *first* rather than the form. Change the `showForm` state variable to initialize to `false` instead of `true`. As soon as you make that change, the console will show that an empty message was sent. Something in this logic is wrong!
+Your app's users are sending way too many messages. To make chatting a little bit more difficult, you've decided to show the "Thank you" dialog *first* rather than the form. Change the `showForm` State variable to initialize to `false` instead of `true`. As soon as you make that change, the console will show that an empty message was sent. Something in this logic is wrong!
What's the root cause of this problem? And how can you fix it?
@@ -1675,7 +1675,7 @@ label, textarea { margin-bottom: 10px; display: block; }
-The `showForm` state variable determines whether to show the form or the "Thank you" dialog. However, you aren't sending the message because the "Thank you" dialog was _displayed_. You want to send the message because the user has _submitted the form._ Delete the misleading Effect and move the `sendMessage` call inside the `handleSubmit` event handler:
+The `showForm` State variable determines whether to show the form or the "Thank you" dialog. However, you aren't sending the message because the "Thank you" dialog was _displayed_. You want to send the message because the user has _submitted the form._ Delete the misleading Effect and move the `sendMessage` call inside the `handleSubmit` event handler:
diff --git a/src/content/reference/react-dom/hooks/useFormState.md b/src/content/reference/react-dom/hooks/useFormState.md
index e2a8d539402..f804dd0f870 100644
--- a/src/content/reference/react-dom/hooks/useFormState.md
+++ b/src/content/reference/react-dom/hooks/useFormState.md
@@ -11,7 +11,7 @@ The `useFormState` Hook is currently only available in React's Canary and experi
-`useFormState` is a Hook that allows you to update state based on the result of a form action.
+`useFormState` is a Hook that allows you to update State based on the result of a form action.
```js
const [state, formAction] = useFormState(fn, initialState, permalink?);
@@ -29,7 +29,7 @@ const [state, formAction] = useFormState(fn, initialState, permalink?);
{/* TODO T164397693: link to actions documentation once it exists */}
-Call `useFormState` at the top level of your component to create component state that is updated [when a form action is invoked](/reference/react-dom/components/form). You pass `useFormState` an existing form action function as well as an initial state, and it returns a new action that you use in your form, along with the latest form state. The latest form state is also passed to the function that you provided.
+Call `useFormState` at the top level of your component to create component state that is updated [when a form action is invoked](/reference/react-dom/components/form). You pass `useFormState` an existing form action function as well as an initial State, and it returns a new action that you use in your form, along with the latest form State. The latest form State is also passed to the function that you provided.
```js
import { useFormState } from "react-dom";
@@ -49,7 +49,7 @@ function StatefulForm({}) {
}
```
-The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass.
+The form State is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial State that you pass.
If used with a Server Action, `useFormState` allows the server's response from submitting the form to be shown even before hydration has completed.
@@ -57,9 +57,9 @@ If used with a Server Action, `useFormState` allows the server's response from s
#### Parameters {/*parameters*/}
-* `fn`: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the `initialState` that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
-* `initialState`: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
-* **optional** `permalink`: A string containing the unique page URL that this form modifies. For use on pages with dynamic content (eg: feeds) in conjunction with progressive enhancement: if `fn` is a [server action](/reference/react/use-server) and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page's URL. Ensure that the same form component is rendered on the destination page (including the same action `fn` and `permalink`) so that React knows how to pass the state through. Once the form has been hydrated, this parameter has no effect.
+* `fn`: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous State of the form (initially the `initialState` that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
+* `initialState`: The value you want the State to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
+* **optional** `permalink`: A string containing the unique page URL that this form modifies. For use on pages with dynamic content (eg: feeds) in conjunction with progressive enhancement: if `fn` is a [server action](/reference/react/use-server) and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page's URL. Ensure that the same form component is rendered on the destination page (including the same action `fn` and `permalink`) so that React knows how to pass the State through. Once the form has been hydrated, this parameter has no effect.
{/* TODO T164397693: link to serializable values docs once it exists */}
@@ -67,13 +67,13 @@ If used with a Server Action, `useFormState` allows the server's response from s
`useFormState` returns an array with exactly two values:
-1. The current state. During the first render, it will match the `initialState` you have passed. After the action is invoked, it will match the value returned by the action.
+1. The current State. During the first render, it will match the `initialState` you have passed. After the action is invoked, it will match the value returned by the action.
2. A new action that you can pass as the `action` prop to your `form` component or `formAction` prop to any `button` component within the form.
#### Caveats {/*caveats*/}
-* When used with a framework that supports React Server Components, `useFormState` lets you make forms interactive before JavaScript has executed on the client. When used without Server Components, it is equivalent to component local state.
-* The function passed to `useFormState` receives an extra argument, the previous or initial state, as its first argument. This makes its signature different than if it were used directly as a form action without using `useFormState`.
+* When used with a framework that supports React Server Components, `useFormState` lets you make forms interactive before JavaScript has executed on the client. When used without Server Components, it is equivalent to component local State.
+* The function passed to `useFormState` receives an extra argument, the previous or initial State, as its first argument. This makes its signature different than if it were used directly as a form action without using `useFormState`.
---
@@ -283,7 +283,7 @@ form button {
### My action can no longer read the submitted form data {/*my-action-can-no-longer-read-the-submitted-form-data*/}
-When you wrap an action with `useFormState`, it gets an extra argument *as its first argument*. The submitted form data is therefore its *second* argument instead of its first as it would usually be. The new first argument that gets added is the current state of the form.
+When you wrap an action with `useFormState`, it gets an extra argument *as its first argument*. The submitted form data is therefore its *second* argument instead of its first as it would usually be. The new first argument that gets added is the current State of the form.
```js
function action(currentState, formData) {
diff --git a/src/content/reference/react-dom/hooks/useFormStatus.md b/src/content/reference/react-dom/hooks/useFormStatus.md
index 70feceaeafc..a37891ef97e 100644
--- a/src/content/reference/react-dom/hooks/useFormStatus.md
+++ b/src/content/reference/react-dom/hooks/useFormStatus.md
@@ -79,8 +79,8 @@ A `status` object with the following properties:
## Usage {/*usage*/}
-### Display a pending state during form submission {/*display-a-pending-state-during-form-submission*/}
-To display a pending state while a form is submitting, you can call the `useFormStatus` Hook in a component rendered in a `