Browse Source

[Beta] Rename Gotcha component to Pitfall (#5172)

The visible name on the site was already Pitfall since a while back, this makes the components use that name too.
main
Alvar Lagerlöf 2 years ago
committed by GitHub
parent
commit
d07016aea8
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      beta/src/components/Icon/IconPitfall.tsx
  2. 10
      beta/src/components/MDX/ExpandableCallout.tsx
  3. 6
      beta/src/components/MDX/MDXComponents.tsx
  4. 4
      beta/src/content/apis/react-dom/client/createRoot.md
  5. 4
      beta/src/content/apis/react-dom/client/hydrateRoot.md
  6. 4
      beta/src/content/apis/react-dom/findDOMNode.md
  7. 8
      beta/src/content/apis/react-dom/flushSync.md
  8. 8
      beta/src/content/apis/react-dom/hydrate.md
  9. 4
      beta/src/content/apis/react-dom/render.md
  10. 20
      beta/src/content/apis/react/Children.md
  11. 4
      beta/src/content/apis/react/Suspense.md
  12. 4
      beta/src/content/apis/react/createFactory.md
  13. 4
      beta/src/content/apis/react/forwardRef.md
  14. 4
      beta/src/content/apis/react/memo.md
  15. 4
      beta/src/content/apis/react/useContext.md
  16. 4
      beta/src/content/apis/react/useEffect.md
  17. 8
      beta/src/content/apis/react/useId.md
  18. 4
      beta/src/content/apis/react/useImperativeHandle.md
  19. 4
      beta/src/content/apis/react/useInsertionEffect.md
  20. 4
      beta/src/content/apis/react/useReducer.md
  21. 4
      beta/src/content/apis/react/useRef.md
  22. 4
      beta/src/content/apis/react/useState.md
  23. 12
      beta/src/content/learn/add-react-to-a-website.md
  24. 4
      beta/src/content/learn/choosing-the-state-structure.md
  25. 4
      beta/src/content/learn/conditional-rendering.md
  26. 4
      beta/src/content/learn/javascript-in-jsx-with-curly-braces.md
  27. 4
      beta/src/content/learn/lifecycle-of-reactive-effects.md
  28. 4
      beta/src/content/learn/passing-props-to-a-component.md
  29. 8
      beta/src/content/learn/preserving-and-resetting-state.md
  30. 4
      beta/src/content/learn/removing-effect-dependencies.md
  31. 4
      beta/src/content/learn/render-and-commit.md
  32. 8
      beta/src/content/learn/rendering-lists.md
  33. 16
      beta/src/content/learn/responding-to-events.md
  34. 4
      beta/src/content/learn/state-a-components-memory.md
  35. 8
      beta/src/content/learn/synchronizing-with-effects.md
  36. 4
      beta/src/content/learn/thinking-in-react.md
  37. 16
      beta/src/content/learn/updating-arrays-in-state.md
  38. 4
      beta/src/content/learn/writing-markup-with-jsx.md
  39. 12
      beta/src/content/learn/your-first-component.md

4
beta/src/components/Icon/IconGotcha.tsx → beta/src/components/Icon/IconPitfall.tsx

@ -4,8 +4,8 @@
import {memo} from 'react';
export const IconGotcha = memo<JSX.IntrinsicElements['svg']>(
function IconGotcha({className}) {
export const IconPitfall = memo<JSX.IntrinsicElements['svg']>(
function IconPitfall({className}) {
return (
<svg
className={className}

10
beta/src/components/MDX/ExpandableCallout.tsx

@ -7,9 +7,9 @@ import * as React from 'react';
import cn from 'classnames';
import {IconNote} from '../Icon/IconNote';
import {IconWarning} from '../Icon/IconWarning';
import {IconGotcha} from '../Icon/IconGotcha';
import {IconPitfall} from '../Icon/IconPitfall';
type CalloutVariants = 'deprecated' | 'gotcha' | 'note' | 'wip';
type CalloutVariants = 'deprecated' | 'pitfall' | 'note' | 'wip';
interface ExpandableCalloutProps {
children: React.ReactNode;
@ -34,9 +34,9 @@ const variantMap = {
overlayGradient:
'linear-gradient(rgba(245, 249, 248, 0), rgba(245, 249, 248, 1)',
},
gotcha: {
pitfall: {
title: 'Pitfall',
Icon: IconGotcha,
Icon: IconPitfall,
containerClasses: 'bg-yellow-5 dark:bg-yellow-60 dark:bg-opacity-20',
textColor: 'text-yellow-50 dark:text-yellow-40',
overlayGradient:
@ -56,6 +56,8 @@ function ExpandableCallout({children, type}: ExpandableCalloutProps) {
const contentRef = useRef<HTMLDivElement>(null);
const variant = variantMap[type];
console.log('v,', variant);
return (
<div
className={cn(

6
beta/src/components/MDX/MDXComponents.tsx

@ -76,8 +76,8 @@ const Divider = () => (
const Wip = ({children}: {children: React.ReactNode}) => (
<ExpandableCallout type="wip">{children}</ExpandableCallout>
);
const Gotcha = ({children}: {children: React.ReactNode}) => (
<ExpandableCallout type="gotcha">{children}</ExpandableCallout>
const Pitfall = ({children}: {children: React.ReactNode}) => (
<ExpandableCallout type="pitfall">{children}</ExpandableCallout>
);
const Deprecated = ({children}: {children: React.ReactNode}) => (
<ExpandableCallout type="deprecated">{children}</ExpandableCallout>
@ -371,7 +371,7 @@ export const MDXComponents = {
MaxWidth({children}: {children: any}) {
return <div className="max-w-4xl ml-0 2xl:mx-auto">{children}</div>;
},
Gotcha,
Pitfall,
Deprecated,
Wip,
HomepageHero,

4
beta/src/content/apis/react-dom/client/createRoot.md

@ -96,11 +96,11 @@ This can feel very slow! To solve this, you can generate the initial HTML from y
</Note>
<Gotcha>
<Pitfall>
**Apps using server rendering or static generation must call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) instead of `createRoot`.** React will then *hydrate* (reuse) the DOM nodes from your HTML instead of destroying and re-creating them.
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react-dom/client/hydrateRoot.md

@ -79,7 +79,7 @@ function Counter() {
You shouldn't need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/apis/react/useState)
<Gotcha>
<Pitfall>
The React tree you pass to `hydrateRoot` needs to produce **the same output** as it did on the server.
@ -94,7 +94,7 @@ The most common causes leading to hydration errors include:
React can recover from some hydration errors, but **you must fix them like other bugs.** In the best case, they'll lead to a slower app; in the worst case, event handlers would get attached to the wrong elements.
</Gotcha>
</Pitfall>
### Updating a hydrated root component {/*updating-a-hydrated-root-component*/}

4
beta/src/content/apis/react-dom/findDOMNode.md

@ -21,8 +21,8 @@ findDOMNode(component)
<InlineToc />
<Gotcha>
<Pitfall>
`findDOMNode` is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. [It has been deprecated in StrictMode.](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage)
</Gotcha>
</Pitfall>

8
beta/src/content/apis/react-dom/flushSync.md

@ -2,11 +2,11 @@
title: flushSync
---
<Gotcha>
<Pitfall>
Using `flushSync` is uncommon and can hurt the performance of your app.
</Gotcha>
</Pitfall>
<Intro>
@ -90,13 +90,13 @@ export default function PrintApp() {
If you remove the call to `flushSync`, then when the print dialog will display `isPrinting` as "no". This is because React batches the updates asynchronously and the print dialog is displayed before the state is updated.
<Gotcha>
<Pitfall>
`flushSync` can significantly hurt performance, and may unexpectedly force pending Suspense boundaries to show their fallback state.
Most of the time, `flushSync` can be avoided, so use `flushSync` as last resort.
</Gotcha>
</Pitfall>
---

8
beta/src/content/apis/react-dom/hydrate.md

@ -1,11 +1,11 @@
---
title: hydrate
---
<Gotcha>
<Pitfall>
In React 18, `hydrate` was replaced by [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Using `hydrate` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)
</Gotcha>
</Pitfall>
<Intro>
@ -155,13 +155,13 @@ export default function App() {
This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration.
<Gotcha>
<Pitfall>
This approach will make your components slower because they have to render twice, so use it with caution.
Remember to be mindful of user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so if you render something different in the client-only pass, the transition can be jarring. However, if executed well, it may be beneficial to render a “shell” of the application on the server, and only show some of the extra widgets on the client. To learn how to do this without getting the markup mismatch issues, refer to the explanation in the previous paragraph.
</Gotcha>
</Pitfall>

4
beta/src/content/apis/react-dom/render.md

@ -2,11 +2,11 @@
title: render
---
<Gotcha>
<Pitfall>
In React 18, `render` was replaced by [`createRoot`.](/apis/react-dom/client/createRoot) Using `render` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)
</Gotcha>
</Pitfall>
<Intro>

20
beta/src/content/apis/react/Children.md

@ -2,11 +2,11 @@
title: Children
---
<Gotcha>
<Pitfall>
Using `Children` is uncommon and can lead to fragile code. [See common alternatives.](#alternatives)
</Gotcha>
</Pitfall>
<Intro>
@ -136,7 +136,7 @@ Even when `children` is an array, `Children.map` has useful special behavior. Fo
</DeepDive>
<Gotcha>
<Pitfall>
The `children` data structure **does not include rendered output** of the components you pass as JSX. In the example below, the `children` received by the `RowList` only contains two items rather than three:
@ -204,7 +204,7 @@ export default function RowList({ children }) {
**There is no way to get the rendered output of an inner component** like `<MoreRows />` when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives)
</Gotcha>
</Pitfall>
---
@ -244,11 +244,11 @@ export default function SeparatorList({ children }) {
</Sandpack>
<Gotcha>
<Pitfall>
As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives)
</Gotcha>
</Pitfall>
---
@ -315,11 +315,11 @@ export default function RowList({ children }) {
</Sandpack>
<Gotcha>
<Pitfall>
As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives)
</Gotcha>
</Pitfall>
---
@ -355,11 +355,11 @@ export default function ReversedList({ children }) {
</Sandpack>
<Gotcha>
<Pitfall>
As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives)
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react/Suspense.md

@ -54,7 +54,7 @@ Suspense will never show unintentional "holes" in your content. For example, if
To reveal nested content as it loads, you need to [add more Suspense boundaries.](#revealing-nested-content-as-it-loads)
<Gotcha>
<Pitfall>
**Only Suspense-enabled data sources will activate a Suspense boundary.** These data sources are said to *suspend* when the data needed to render has not yet loaded. Currently, Suspense is only supported for:
@ -65,7 +65,7 @@ Suspense-enabled data fetching without the use of an opinionated framework is no
Suspense does not detect when data is fetched inside an Effect or event handler.
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react/createFactory.md

@ -175,7 +175,7 @@ export default function App() {
</Sandpack>
<Gotcha>
<Pitfall>
Sometimes, your existing code might pass some variable as a `type` instead of a constant like `'button'`:
@ -198,7 +198,7 @@ function Heading({ isSubheading, ...props }) {
Otherwise React will interpret `<type>` as a built-in HTML tag because it is lowercase.
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react/forwardRef.md

@ -407,13 +407,13 @@ input {
[Read more about using imperative handles.](/apis/react/useImperativeHandle)
<Gotcha>
<Pitfall>
**Do not overuse refs.** You should only use refs for *imperative* behaviors that you can't express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react/memo.md

@ -317,13 +317,13 @@ If you do this, use the Performance panel in your browser developer tools to mak
When you do performance measurements, make sure that React is running in the production mode.
<Gotcha>
<Pitfall>
If you provide a custom `arePropsEqual` implementation, **you must compare every prop, including functions.** Functions often [close over](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) the props and state of parent components. If you return `true` when `oldProps.onClick !== newProps.onClick`, your component will keep "seeing" the props and state from a previous render inside its `onClick` handler, leading to very confusing bugs.
Avoid doing deep equality checks inside `arePropsEqual` unless you are 100% sure that the data structure you're working with has a known limited depth. **Deep equality checks can become incredibly slow** and can freeze your app for many seconds if someone changes the data structure later.
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react/useContext.md

@ -51,11 +51,11 @@ function Form() {
It doesn't matter how many layers of components there are between the provider and the `Button`. When a `Button` *anywhere* inside of `Form` calls `useContext(ThemeContext)`, it will receive `"dark"` as the value.
<Gotcha>
<Pitfall>
`useContext()` always looks for the closest provider *above* the component that calls it. It searches upwards and **does not** consider providers in the component from which you're calling `useContext()`.
</Gotcha>
</Pitfall>
<Sandpack>

4
beta/src/content/apis/react/useEffect.md

@ -1066,7 +1066,7 @@ function ChatRoom() {
[An Effect with empty dependencies](/learn/lifecycle-of-reactive-effects#what-an-effect-with-empty-dependencies-means) doesn't re-run when any of your component's props or state change.
<Gotcha>
<Pitfall>
If you have an existing codebase, you might have some Effects that suppress the linter like this:
@ -1080,7 +1080,7 @@ useEffect(() => {
**When dependencies don't match the code, there is a high risk of introducing bugs.** By suppressing the linter, you "lie" to React about the values your Effect depends on. [Instead, prove they're unnecessary.](/learn/removing-effect-dependencies#removing-unnecessary-dependencies)
</Gotcha>
</Pitfall>
<Recipes titleText="Examples of passing reactive dependencies" titleId="examples-dependencies">

8
beta/src/content/apis/react/useId.md

@ -18,11 +18,11 @@ const id = useId()
## Usage {/*usage*/}
<Gotcha>
<Pitfall>
**Do not call `useId` to generate keys in a list.** [Keys should be generated from your data.](/learn/rendering-lists#where-to-get-your-key)
</Gotcha>
</Pitfall>
### Generating unique IDs for accessibility attributes {/*generating-unique-ids-for-accessibility-attributes*/}
@ -133,11 +133,11 @@ input { margin: 5px; }
[Watch this video](https://www.youtube.com/watch?v=0dNzNcuEuOo) to see the difference in the user experience with assistive technologies.
<Gotcha>
<Pitfall>
**`useId` requires an identical component tree on the server and the client** when you use [server rendering](/apis/react-dom/server). If the trees you render on the server and the client don't match exactly, the generated IDs won't match.
</Gotcha>
</Pitfall>
<DeepDive title="Why is useId better than an incrementing counter?">

4
beta/src/content/apis/react/useImperativeHandle.md

@ -245,13 +245,13 @@ export default AddComment;
</Sandpack>
<Gotcha>
<Pitfall>
**Do not overuse refs.** You should only use refs for *imperative* behaviors that you can't express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react/useInsertionEffect.md

@ -21,8 +21,8 @@ useInsertionEffect(didUpdate);
<InlineToc />
<Gotcha>
<Pitfall>
`useInsertionEffect` should be limited to css-in-js library authors. Prefer [`useEffect`](/apis/react/useEffect) or [`useLayoutEffect`](/apis/react/useLayoutEffect) instead.
</Gotcha>
</Pitfall>

4
beta/src/content/apis/react/useReducer.md

@ -144,7 +144,7 @@ The action type names are local to your component. [Each action describes a sing
Read [extracting state logic into a reducer](/learn/extracting-state-logic-into-a-reducer) to learn more.
<Gotcha>
<Pitfall>
State is read-only. Don't modify any objects or arrays in state:
@ -174,7 +174,7 @@ function reducer(state, action) {
Read [updating objects in state](/learn/updating-objects-in-state) and [updating arrays in state](/learn/updating-arrays-in-state) to learn more.
</Gotcha>
</Pitfall>
<Recipes titleText="Basic useReducer examples" titleId="examples-basic">

4
beta/src/content/apis/react/useRef.md

@ -148,7 +148,7 @@ export default function Stopwatch() {
</Recipes>
<Gotcha>
<Pitfall>
**Do not write _or read_ `ref.current` during rendering.**
@ -192,7 +192,7 @@ If you *have to* read [or write](/apis/react/useState#storing-information-from-p
When you break these rules, your component might still work, but most of the newer features we're adding to React will rely on these expectations. Read more about [keeping your components pure.](/learn/keeping-components-pure#where-you-can-cause-side-effects)
</Gotcha>
</Pitfall>
---

4
beta/src/content/apis/react/useState.md

@ -48,7 +48,7 @@ function handleClick() {
React will store the next state, render your component again with the new values, and update the UI.
<Gotcha>
<Pitfall>
Calling the `set` function [**does not** change the current state in the already executing code](#ive-updated-the-state-but-logging-gives-me-the-old-value):
@ -61,7 +61,7 @@ function handleClick() {
It only affects what `useState` will return starting from the *next* render.
</Gotcha>
</Pitfall>
<Recipes titleText="Basic useState examples" titleId="examples-basic">

12
beta/src/content/learn/add-react-to-a-website.md

@ -57,11 +57,11 @@ Your HTML should now end like this:
</html>
```
<Gotcha>
<Pitfall>
Before deploying to a live website, make sure to replace `development.js` with `production.min.js`! Development builds of React provide more helpful error messages, but slow down your website *a lot.*
</Gotcha>
</Pitfall>
### Step 3: Create a React component {/*step-3-create-a-react-component*/}
@ -183,11 +183,11 @@ return (
It may feel a bit unusual at first to mix JS with markup, but it will grow on you! Check out [Writing Markup in JSX](/learn/writing-markup-with-jsx) for an introduction. Here is [an example HTML file with JSX](https://raw.githubusercontent.com/reactjs/reactjs.org/main/static/html/single-file-example.html) that you can download and play with.
<Gotcha>
<Pitfall>
The Babel `<script>` compiler is fine for learning and creating simple demos. However, **it makes your website slow and isn't suitable for production.** When you're ready to move forward, remove the Babel `<script>` tag and remove the `type="text/babel"` attribute you've added in this step. Instead, in the next section you will set up a JSX preprocessor to convert all your `<script>` tags from JSX to JS.
</Gotcha>
</Pitfall>
### Add JSX to a project {/*add-jsx-to-a-project*/}
@ -212,11 +212,11 @@ You can preprocess JSX so that every time you save a file with JSX in it, the tr
The watcher will create a preprocessed **`like-button.js`** with the plain JavaScript code suitable for the browser.
<Gotcha>
<Pitfall>
If you see an error message saying "You have mistakenly installed the `babel` package", you might have missed [the previous step.](#add-jsx-to-a-project) Perform it in the same folder, and then try again.
</Gotcha>
</Pitfall>
The tool you just used is called Babel, and you can learn more about it from [its documentation.](https://babeljs.io/docs/en/babel-cli/) In addition to JSX, it lets you use the most recent JavaScript syntax features without worrying about breaking older browsers.

4
beta/src/content/learn/choosing-the-state-structure.md

@ -95,11 +95,11 @@ 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 different pieces of state you'll need. For example, it's helpful when you have a form where the user can add custom fields.
<Gotcha>
<Pitfall>
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)`.
</Gotcha>
</Pitfall>
## Avoid contradictions in state {/*avoid-contradictions-in-state*/}

4
beta/src/content/learn/conditional-rendering.md

@ -311,7 +311,7 @@ export default function PackingList() {
A [JavaScript && expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) returns the value of its right side (in our case, the checkmark) if the left side (our condition) is `true`. But if the condition is `false`, the whole expression becomes `false`. React considers `false` as a "hole" in the JSX tree, just like `null` or `undefined`, and doesn't render anything in its place.
<Gotcha>
<Pitfall>
**Don't put numbers on the left side of `&&`.**
@ -321,7 +321,7 @@ For example, a common mistake is to write code like `messageCount && <p>New mess
To fix it, make the left side a boolean: `messageCount > 0 && <p>New messages</p>`.
</Gotcha>
</Pitfall>
### Conditionally assigning JSX to a variable {/*conditionally-assigning-jsx-to-a-variable*/}

4
beta/src/content/learn/javascript-in-jsx-with-curly-braces.md

@ -163,11 +163,11 @@ You can really see the JavaScript object inside the curly braces when you write
The next time you see `{{` and `}}` in JSX, know that it's nothing more than an object inside the JSX curlies!
<Gotcha>
<Pitfall>
Inline `style` properties are written in camelCase. For example, HTML `<ul style="background-color: black">` would be written as `<ul style={{ backgroundColor: 'black' }}>` in your component.
</Gotcha>
</Pitfall>
## More fun with JavaScript objects and curly braces {/*more-fun-with-javascript-objects-and-curly-braces*/}

4
beta/src/content/learn/lifecycle-of-reactive-effects.md

@ -736,7 +736,7 @@ function ChatRoom() {
* **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 your Effects.](/learn/removing-effect-dependencies)
<Gotcha>
<Pitfall>
The linter is your friend, but its powers are limited. The linter only knows when the dependencies are *wrong*. It doesn't know *the best* way to solve each case. If the linter suggests a dependency, but adding it causes a loop, it doesn't mean the linter should be ignored. It means you need to change the code inside (or outside) the Effect so that that value isn't reactive and doesn't *need* to be a dependency.
@ -752,7 +752,7 @@ useEffect(() => {
On the [next](/learn/separating-events-from-effects) [pages](/learn/removing-effect-dependencies), you'll learn how to fix this code without breaking the rules. It's always worth fixing!
</Gotcha>
</Pitfall>
<Recap>

4
beta/src/content/learn/passing-props-to-a-component.md

@ -178,7 +178,7 @@ function Avatar(props) {
Usually you don't need the whole `props` object itself, so you destructure it into individual props.
<Gotcha>
<Pitfall>
**Don't miss the pair of `{` and `}` curlies** inside of `(` and `)` when declaring props:
@ -198,7 +198,7 @@ function Avatar(props) {
}
```
</Gotcha>
</Pitfall>
## Specifying a default value for a prop {/*specifying-a-default-value-for-a-prop*/}

8
beta/src/content/learn/preserving-and-resetting-state.md

@ -392,7 +392,7 @@ Updating the `App` state does not reset the `Counter` because `Counter` stays in
It's the same component at the same position, so from React's perspective, it's the same counter.
<Gotcha>
<Pitfall>
Remember that **it's the position in the UI tree--not in the JSX markup--that matters to React!** This component has two `return` clauses with different `<Counter />` JSX tags inside and outside the `if`:
@ -496,7 +496,7 @@ You might expect the state to reset when you tick checkbox, but it doesn't! This
You can think of them as having 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.
</Gotcha>
</Pitfall>
## Different components at the same position reset state {/*different-components-at-the-same-position-reset-state*/}
@ -712,7 +712,7 @@ When switching back, the `div` is deleted and the new `section` is added
As a rule of thumb, **if you want to preserve the state between re-renders, the structure of your tree needs to "match up"** from one render to another. If the structure is different, the state gets destroyed because React destroys state when it removes a component from the tree.
<Gotcha>
<Pitfall>
This is why you should not nest component function definitions.
@ -753,7 +753,7 @@ export default function MyComponent() {
Every time you click the button, the input state disappears! This is because a *different* `MyTextField` function is created for every render of `MyComponent`. You're rendering a *different* component in the same position, so React resets all state below. This leads to bugs and performance problems. To avoid this problem, **always declare component functions at the top level, and don't nest their definitions.**
</Gotcha>
</Pitfall>
## Resetting state at the same position {/*resetting-state-at-the-same-position*/}

4
beta/src/content/learn/removing-effect-dependencies.md

@ -277,7 +277,7 @@ The last part is important. **If you want to change the dependencies, change the
This might feel like solving an equation. You might start with a goal (for example, to remove a dependency), and you need to "find" the exact code matching that goal. Not everyone finds solving equations fun, and the same thing could be said about writing Effects! Luckily, there is a list of common recipes that you can try below.
<Gotcha>
<Pitfall>
If you have an existing codebase, you might have some Effects that suppress the linter like this:
@ -291,7 +291,7 @@ useEffect(() => {
**When dependencies don't match the code, there is a very high risk of introducing bugs.** By suppressing the linter, you "lie" to React about the values your Effect depends on. Instead, use the techniques below.
</Gotcha>
</Pitfall>
<DeepDive title="Why is suppressing the dependency linter so dangerous?">

4
beta/src/content/learn/render-and-commit.md

@ -127,7 +127,7 @@ img { margin: 0 10px 10px 0; }
* **During the initial render,** React will [create the DOM nodes](https://developer.mozilla.org/docs/Web/API/Document/createElement) for `<section>`, `<h1>`, and three `<img>` tags.
* **During a re-render,** React will calculate which of their properties, if any, have changed since the previous render. It won't do anything with that information until the next step, the commit phase.
<Gotcha>
<Pitfall>
Rendering must always be a [pure calculation](/learn/keeping-components-pure):
@ -136,7 +136,7 @@ Rendering must always be a [pure calculation](/learn/keeping-components-pure):
Otherwise, you can encounter confusing bugs and unpredictable behavior as your codebase grows in complexity. When developing in "Strict Mode", React calls each component's function twice, which can help surface mistakes caused by impure functions.
</Gotcha>
</Pitfall>
<DeepDive title="Optimizing performance">

8
beta/src/content/learn/rendering-lists.md

@ -242,7 +242,7 @@ img { width: 100px; height: 100px; border-radius: 50%; }
</Sandpack>
<Gotcha>
<Pitfall>
Arrow functions implicitly return the expression right after `=>`, so you didn't need a `return` statement:
@ -262,7 +262,7 @@ const listItems = chemists.map(person => { // Curly brace
Arrow functions containing `=> {` are said to have a ["block body".](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#function_body) They let you write more than a single line of code, but you *have to* write a `return` statement yourself. If you forget it, nothing gets returned!
</Gotcha>
</Pitfall>
## Keeping list items in order with `key` {/*keeping-list-items-in-order-with-key*/}
@ -413,7 +413,7 @@ Imagine that files on your desktop didn't have names. Instead, you'd refer to th
File names in a folder and JSX keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the _position_ changes due to reordering, the `key` lets React identify the item throughout its lifetime.
<Gotcha>
<Pitfall>
You might be tempted to use an item's index in the array as its key. In fact, that's what React will use if you don't specify a `key` at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.
@ -421,7 +421,7 @@ Similarly, do not generate keys on the fly, e.g. with `key={Math.random()}`. Thi
Note that your components won't receive `key` as a prop. It's only used as a hint by React itself. If your component needs an ID, you have to pass it as a separate prop: `<Profile key={id} userId={id} />`.
</Gotcha>
</Pitfall>
<Recap>

16
beta/src/content/learn/responding-to-events.md

@ -87,12 +87,12 @@ Or, more concisely, using an arrow function:
All of these styles are equivalent. Inline event handlers are convenient for short functions.
<Gotcha>
<Pitfall>
Functions passed to event handlers must be passed, not called. For example:
| passing a function (correct) | calling a function (incorrect) |
|----------------------------------------|--------------------------------|
| passing a function (correct) | calling a function (incorrect) |
| -------------------------------- | ---------------------------------- |
| `<button onClick={handleClick}>` | `<button onClick={handleClick()}>` |
The difference is subtle. In the first example, the `handleClick` function is passed as an `onClick` event handler. This tells React to remember it and only call your function when the user clicks the button.
@ -101,8 +101,8 @@ In the second example, the `()` at the end of `handleClick()` fires the function
When you write code inline, the same pitfall presents itself in a different way:
| passing a function (correct) | calling a function (incorrect) |
|----------------------------------------|--------------------------------|
| passing a function (correct) | calling a function (incorrect) |
| --------------------------------------- | --------------------------------- |
| `<button onClick={() => alert('...')}>` | `<button onClick={alert('...')}>` |
@ -128,7 +128,7 @@ In both cases, what you want to pass is a function:
> [Read more about arrow functions.](https://javascript.info/arrow-functions-basics)
</Gotcha>
</Pitfall>
### Reading props in event handlers {/*reading-props-in-event-handlers*/}
@ -351,11 +351,11 @@ button { margin: 5px; }
If you click on either button, its `onClick` will run first, followed by the parent `<div>`'s `onClick`. So two messages will appear. If you click the toolbar itself, only the parent `<div>`'s `onClick` will run.
<Gotcha>
<Pitfall>
All events propagate in React except `onScroll`, which only works on the JSX tag you attach it to.
</Gotcha>
</Pitfall>
### Stopping propagation {/*stopping-propagation*/}

4
beta/src/content/learn/state-a-components-memory.md

@ -339,11 +339,11 @@ In React, `useState`, as well as any other function starting with "`use`", is ca
State is just one of those features, but you will meet the other Hooks later.
<Gotcha>
<Pitfall>
**Hooks—functions starting with `use`—can only be called at the top level of your components or [your own Hooks.](/learn/reusing-logic-with-custom-hooks)** You can't call Hooks inside conditions, loops, or other nested functions. Hooks are functions, but it's helpful to think of them as unconditional declarations about your component's needs. You "use" React features at the top of your component similar to how you "import" modules at the top of your file.
</Gotcha>
</Pitfall>
### Anatomy of `useState` {/*anatomy-of-usestate*/}

8
beta/src/content/learn/synchronizing-with-effects.md

@ -209,7 +209,7 @@ In this example, the "external system" you synchronized to React state was the b
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.
<Gotcha>
<Pitfall>
By default, Effects run after *every* render. This is why code like this will **produce an infinite loop:**
@ -224,7 +224,7 @@ Effects run as a *result* of rendering. Setting state *triggers* rendering. Sett
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)
</Gotcha>
</Pitfall>
### Step 2: Specify the Effect dependencies {/*step-2-specify-the-effect-dependencies*/}
@ -401,7 +401,7 @@ The dependency array can contain multiple dependencies. React will only skip re-
**Notice that you can't "choose" your dependencies.** You will get a lint error if the dependencies you specified don't match what React expects based on the code inside your Effect. This helps catch many bugs in your code. If your Effect uses some value but you *don't* want to re-run the Effect when it changes, you'll need to [*edit the Effect code itself* to not "need" that dependency.](/learn/lifecycle-of-reactive-effects#what-to-do-when-you-dont-want-to-re-synchronize)
<Gotcha>
<Pitfall>
The behaviors *without* the dependency array and with an *empty* `[]` dependency array are very different:
@ -421,7 +421,7 @@ useEffect(() => {
We'll take a close look at what "mount" means in the next step.
</Gotcha>
</Pitfall>
<DeepDive title="Why was the ref omitted from the dependency array?">

4
beta/src/content/learn/thinking-in-react.md

@ -199,11 +199,11 @@ td {
After building your components, you'll have a library of reusable components that render your data model. Because this is a static app, the components will only return JSX. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. This is called _one-way data flow_ because the data flows down from the top-level component to the ones at the bottom of the tree.
<Gotcha>
<Pitfall>
At this point, you should not be using any state values. That’s for the next step!
</Gotcha>
</Pitfall>
## Step 3: Find the minimal but complete representation of UI state {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/}

16
beta/src/content/learn/updating-arrays-in-state.md

@ -24,16 +24,16 @@ Instead, every time you want to update an array, you'll want to pass a *new* arr
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) |
|---------|----------------|-------------------|
| adding | `push`, `unshift` | `concat`, `[...arr]` spread syntax ([example](#adding-to-an-array))|
| removing | `pop`, `shift`, `splice` | `filter`, `slice` ([example](#removing-from-an-array))
|replacing| `splice`, `arr[i] = ...` assignment | `map` ([example](#replacing-items-in-an-array)) |
|sorting| `reverse`, `sort` | copy the array first ([example](#making-other-changes-to-an-array)) |
| | avoid (mutates the array) | prefer (returns a new array) |
| --------- | ----------------------------------- | ------------------------------------------------------------------- |
| adding | `push`, `unshift` | `concat`, `[...arr]` spread syntax ([example](#adding-to-an-array)) |
| removing | `pop`, `shift`, `splice` | `filter`, `slice` ([example](#removing-from-an-array)) |
| replacing | `splice`, `arr[i] = ...` assignment | `map` ([example](#replacing-items-in-an-array)) |
| sorting | `reverse`, `sort` | copy the array first ([example](#making-other-changes-to-an-array)) |
Alternatively, you can [use Immer](#write-concise-update-logic-with-immer) which lets you use methods from both columns.
<Gotcha>
<Pitfall>
Unfortunately, [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) and [`splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) are named similarly but are very different:
@ -42,7 +42,7 @@ Unfortunately, [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript
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.
</Gotcha>
</Pitfall>
### Adding to an array {/*adding-to-an-array*/}

4
beta/src/content/learn/writing-markup-with-jsx.md

@ -214,11 +214,11 @@ This is why, in React, many HTML and SVG attributes are written in camelCase. Fo
You can [find all these attributes in the React DOM Elements.](TODO) If you get one wrong, don't worry—React will print a message with a possible correction to the [browser console.](https://developer.mozilla.org/docs/Tools/Browser_Console)
<Gotcha>
<Pitfall>
For historical reasons, [`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) and [`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes) attributes are written as in HTML with dashes.
</Gotcha>
</Pitfall>
### Pro-tip: Use a JSX Converter {/*pro-tip-use-a-jsx-converter*/}

12
beta/src/content/learn/your-first-component.md

@ -86,11 +86,11 @@ The `export default` prefix is a [standard JavaScript syntax](https://developer.
With `function Profile() { }` you define a JavaScript function with the name `Profile`.
<Gotcha>
<Pitfall>
React components are regular JavaScript functions, but **their names must start with a capital letter** or they won't work!
</Gotcha>
</Pitfall>
### Step 3: Add markup {/*step-3-add-markup*/}
@ -112,11 +112,11 @@ return (
);
```
<Gotcha>
<Pitfall>
Without parentheses, any code on the lines after `return` [will be ignored](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)!
</Gotcha>
</Pitfall>
## Using a component {/*using-a-component*/}
@ -176,7 +176,7 @@ Components are regular JavaScript functions, so you can keep multiple components
Because the `Profile` components are rendered inside `Gallery`—even several times!—we can say that `Gallery` is a **parent component,** rendering each `Profile` as a "child". This is part of the magic of React: you can define a component once, and then use it in as many places and as many times as you like.
<Gotcha>
<Pitfall>
Components can render other components, but **you must never nest their definitions:**
@ -205,7 +205,7 @@ function Profile() {
When a child component needs some data from a parent, [pass it by props](/learn/passing-props-to-a-component) instead of nesting definitions.
</Gotcha>
</Pitfall>
<DeepDive title="Components all the way down">

Loading…
Cancel
Save