diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml index 87dcfdc73..b1ef428d0 100644 --- a/.github/workflows/analyze.yml +++ b/.github/workflows/analyze.yml @@ -11,18 +11,26 @@ jobs: analyze: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up node - uses: actions/setup-node@v1 + uses: actions/setup-node@v4 with: node-version: '20.x' + cache: yarn + cache-dependency-path: yarn.lock - - name: Install dependencies - uses: bahmutov/npm-install@v1.7.10 + - name: Restore cached node_modules + uses: actions/cache@v4 + with: + path: "**/node_modules" + key: node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + + - name: Install deps + run: yarn install --frozen-lockfile - name: Restore next build - uses: actions/cache@v2 + uses: actions/cache@v4 id: restore-build-cache env: cache-name: cache-next-build @@ -41,7 +49,7 @@ jobs: run: npx -p nextjs-bundle-analysis@0.5.0 report - name: Upload bundle - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: path: .next/analyze/__bundle_analysis.json name: bundle_analysis.json @@ -73,7 +81,7 @@ jobs: run: ls -laR .next/analyze/base && npx -p nextjs-bundle-analysis compare - name: Upload analysis comment - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: analysis_comment.txt path: .next/analyze/__bundle_analysis_comment.txt @@ -82,7 +90,7 @@ jobs: run: echo ${{ github.event.number }} > ./pr_number - name: Upload PR number - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: pr_number path: ./pr_number diff --git a/.github/workflows/site_lint.yml b/.github/workflows/site_lint.yml index 34ca6d7b8..36f7642c9 100644 --- a/.github/workflows/site_lint.yml +++ b/.github/workflows/site_lint.yml @@ -14,14 +14,22 @@ jobs: name: Lint on node 20.x and ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 - name: Use Node.js 20.x - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: 20.x + cache: yarn + cache-dependency-path: yarn.lock - - name: Install deps and build (with cache) - uses: bahmutov/npm-install@v1.8.32 + - name: Restore cached node_modules + uses: actions/cache@v4 + with: + path: "**/node_modules" + key: node_modules-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + + - name: Install deps + run: yarn install --frozen-lockfile - name: Lint codebase run: yarn ci-check diff --git a/README.md b/README.md index c90261be0..552c7cd45 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ This repo contains the source code and documentation powering [uk.react.dev](htt ### Prerequisites 1. Git -1. Node: any 12.x version starting with v12.0.0 or greater +1. Node: any version starting with v16.8.0 or greater 1. Yarn: See [Yarn website for installation instructions](https://yarnpkg.com/lang/en/docs/install/) 1. A fork of the repo (for any contributions) 1. A clone of the [uk.react.dev repo](https://github.com/reactjs/uk.react.dev) on your local machine diff --git a/TRANSLATION.md b/TRANSLATION.md index 439817f82..a7aec3ceb 100644 --- a/TRANSLATION.md +++ b/TRANSLATION.md @@ -16,6 +16,18 @@ - Вичитуйте тексти, що перекладені за допомогою зовнішніх сервісів (Google Translate, ChatGPT тощо). - Якщо український відповідник є рідковживаним або має декілька значень, то краще залишити після нього оригінальне слово у дужках, щоб полегшити розуміння читачем. +### Заміна посилань + +Потрібно замінювати посилання на матеріал англійською посиланням на його переклад українською, якщо такий переклад існує. Нижче наведена таблиця вебсайтів, що мають українські відповідники, де варто шукати заміну зовнішнім посиланням. + +| Оригінальний сайт | Варіант українською | +| --------------------- | ------------------- | +| en.wikipedia.org | uk.wikipedia.org | +| javascript.info | uk.javascript.info | +| developer.mozilla.org | webdoky.org | + +Цей список не є вичерпним. + ## Процес перевірки перекладу 1. Мейнтейнер переглядає усі змінені файли PR'у. @@ -73,6 +85,17 @@ | Орудний | _бандлером_ | _бандлерами_ | | Місцевий | _бандлері_ | _бандлерах_ | +Снепшот + +| Відмінок | Однина | Множина | +| --------- | ----------------------- | ------------ | +| Називний | _снепшот_ | _снепшоти_ | +| Родовий | _снепшоту_ | _снепшотів_ | +| Давальний | _снепшоту_/_снепшотові_ | _снепшотам_ | +| Знахідний | _снепшот_ | _снепшоти_ | +| Орудний | _снепшотом_ | _снепшотами_ | +| Місцевий | _снепшоті_/_cнепшотові_ | _снепшотах_ | + ## Таблиця перекладів | Оригінал | Переклад | @@ -159,9 +182,11 @@ | shallow | поверхове(а) (порівняння, рівність), поверховий (рендер) | | side effect | побічний ефект | | single-page application | односторінковий застосунок | +| snapshot | снепшот | | state | стан | | stateful component | компонент зі станом | | stateless component | компонент без стану | +| strict mode | суворий режим | | suspense | затримка | | tag | тег | | template literals | шаблонні рядки | diff --git a/package.json b/package.json index 1f63eb121..ad9b9baa4 100644 --- a/package.json +++ b/package.json @@ -24,8 +24,8 @@ }, "dependencies": { "@codesandbox/sandpack-react": "2.13.5", - "@docsearch/css": "3.0.0-alpha.41", - "@docsearch/react": "3.0.0-alpha.41", + "@docsearch/css": "^3.6.1", + "@docsearch/react": "^3.6.1", "@headlessui/react": "^1.7.0", "@radix-ui/react-context-menu": "^2.1.5", "body-scroll-lock": "^3.1.3", diff --git a/public/.well-known/atproto-did b/public/.well-known/atproto-did new file mode 100644 index 000000000..ad8b0a36b --- /dev/null +++ b/public/.well-known/atproto-did @@ -0,0 +1 @@ +did:plc:uorpbnp2q32vuvyeruwauyhe \ No newline at end of file diff --git a/public/images/docs/diagrams/prerender.dark.png b/public/images/docs/diagrams/prerender.dark.png new file mode 100644 index 000000000..1e7d67e13 Binary files /dev/null and b/public/images/docs/diagrams/prerender.dark.png differ diff --git a/public/images/docs/diagrams/prerender.png b/public/images/docs/diagrams/prerender.png new file mode 100644 index 000000000..ababa5493 Binary files /dev/null and b/public/images/docs/diagrams/prerender.png differ diff --git a/public/images/docs/diagrams/prewarm.dark.png b/public/images/docs/diagrams/prewarm.dark.png new file mode 100644 index 000000000..461406039 Binary files /dev/null and b/public/images/docs/diagrams/prewarm.dark.png differ diff --git a/public/images/docs/diagrams/prewarm.png b/public/images/docs/diagrams/prewarm.png new file mode 100644 index 000000000..f6ec1c49d Binary files /dev/null and b/public/images/docs/diagrams/prewarm.png differ diff --git a/public/images/team/lauren.jpg b/public/images/team/lauren.jpg index cb08b9725..26d46bd2f 100644 Binary files a/public/images/team/lauren.jpg and b/public/images/team/lauren.jpg differ diff --git a/src/components/Icon/IconBsky.tsx b/src/components/Icon/IconBsky.tsx new file mode 100644 index 000000000..6645152dd --- /dev/null +++ b/src/components/Icon/IconBsky.tsx @@ -0,0 +1,24 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + */ + +import {memo} from 'react'; + +export const IconBsky = memo(function IconBsky( + props +) { + return ( + + + + ); +}); diff --git a/src/components/Icon/IconRocket.tsx b/src/components/Icon/IconRocket.tsx new file mode 100644 index 000000000..457736c7c --- /dev/null +++ b/src/components/Icon/IconRocket.tsx @@ -0,0 +1,32 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + */ + +import {memo} from 'react'; + +export const IconRocket = memo< + JSX.IntrinsicElements['svg'] & {title?: string; size?: 's' | 'md'} +>(function IconRocket({className, size = 'md'}) { + return ( + + ); +}); diff --git a/src/components/Layout/Footer.tsx b/src/components/Layout/Footer.tsx index 5bcf9df98..9cdf256fb 100644 --- a/src/components/Layout/Footer.tsx +++ b/src/components/Layout/Footer.tsx @@ -8,6 +8,7 @@ import cn from 'classnames'; import {ExternalLink} from 'components/ExternalLink'; import {IconFacebookCircle} from 'components/Icon/IconFacebookCircle'; import {IconTwitter} from 'components/Icon/IconTwitter'; +import {IconBsky} from 'components/Icon/IconBsky'; import {IconGitHub} from 'components/Icon/IconGitHub'; export function Footer() { @@ -283,7 +284,7 @@ export function Footer() {
- ©{new Date().getFullYear()} + Copyright © Meta Platforms, Inc
+ + + {title}{' '} - {canary && ( + {version === 'major' && ( + + React 19 + + )} + {version === 'canary' && ( )}
diff --git a/src/components/Layout/Sidebar/SidebarRouteTree.tsx b/src/components/Layout/Sidebar/SidebarRouteTree.tsx index 3f058073c..54f02b925 100644 --- a/src/components/Layout/Sidebar/SidebarRouteTree.tsx +++ b/src/components/Layout/Sidebar/SidebarRouteTree.tsx @@ -87,7 +87,7 @@ export function SidebarRouteTree({ path, title, routes, - canary, + version, heading, hasSectionHeader, sectionHeader, @@ -121,7 +121,7 @@ export function SidebarRouteTree({ selected={selected} level={level} title={title} - canary={canary} + version={version} isExpanded={isExpanded} hideArrow={isForceExpanded} /> @@ -145,7 +145,7 @@ export function SidebarRouteTree({ selected={selected} level={level} title={title} - canary={canary} + version={version} /> ); diff --git a/src/components/Layout/getRouteMeta.tsx b/src/components/Layout/getRouteMeta.tsx index 3564dd738..b3d14725d 100644 --- a/src/components/Layout/getRouteMeta.tsx +++ b/src/components/Layout/getRouteMeta.tsx @@ -19,8 +19,8 @@ export type RouteTag = export interface RouteItem { /** Page title (for the sidebar) */ title: string; - /** Optional canary flag for heading */ - canary?: boolean; + /** Optional version flag for heading */ + version?: 'canary' | 'major'; /** Optional page description for heading */ description?: string; /* Additional meta info for page tagging */ diff --git a/src/components/MDX/Diagram.tsx b/src/components/MDX/Diagram.tsx index 7920661da..649f48dff 100644 --- a/src/components/MDX/Diagram.tsx +++ b/src/components/MDX/Diagram.tsx @@ -15,8 +15,8 @@ interface DiagramProps { function Caption({text}: {text: string}) { return ( -
-
+
+
{text}
diff --git a/src/components/MDX/ExpandableCallout.tsx b/src/components/MDX/ExpandableCallout.tsx index 415d5d867..5f594063d 100644 --- a/src/components/MDX/ExpandableCallout.tsx +++ b/src/components/MDX/ExpandableCallout.tsx @@ -8,8 +8,16 @@ import {IconNote} from '../Icon/IconNote'; import {IconWarning} from '../Icon/IconWarning'; import {IconPitfall} from '../Icon/IconPitfall'; import {IconCanary} from '../Icon/IconCanary'; +import {IconRocket} from '../Icon/IconRocket'; -type CalloutVariants = 'deprecated' | 'pitfall' | 'note' | 'wip' | 'canary'; +type CalloutVariants = + | 'deprecated' + | 'pitfall' + | 'note' + | 'wip' + | 'canary' + | 'major' + | 'rsc'; interface ExpandableCalloutProps { children: React.ReactNode; @@ -59,6 +67,22 @@ const variantMap = { overlayGradient: 'linear-gradient(rgba(249, 247, 243, 0), rgba(249, 247, 243, 1)', }, + major: { + title: 'React 19', + Icon: IconRocket, + containerClasses: 'bg-blue-10 dark:bg-blue-60 dark:bg-opacity-20', + textColor: 'text-blue-50 dark:text-blue-40', + overlayGradient: + 'linear-gradient(rgba(249, 247, 243, 0), rgba(249, 247, 243, 1)', + }, + rsc: { + title: 'React Server Components', + Icon: null, + containerClasses: 'bg-blue-10 dark:bg-blue-60 dark:bg-opacity-20', + textColor: 'text-blue-50 dark:text-blue-40', + overlayGradient: + 'linear-gradient(rgba(249, 247, 243, 0), rgba(249, 247, 243, 1)', + }, }; function ExpandableCallout({children, type = 'note'}: ExpandableCalloutProps) { @@ -72,9 +96,11 @@ function ExpandableCallout({children, type = 'note'}: ExpandableCalloutProps) { variant.containerClasses )}>

- + {variant.Icon && ( + + )} {variant.title}

diff --git a/src/components/MDX/MDXComponents.tsx b/src/components/MDX/MDXComponents.tsx index 6f99121f7..0e22c7921 100644 --- a/src/components/MDX/MDXComponents.tsx +++ b/src/components/MDX/MDXComponents.tsx @@ -97,6 +97,14 @@ const Canary = ({children}: {children: React.ReactNode}) => ( {children} ); +const NextMajor = ({children}: {children: React.ReactNode}) => ( + {children} +); + +const RSC = ({children}: {children: React.ReactNode}) => ( + {children} +); + const CanaryBadge = ({title}: {title: string}) => ( ( ); +const NextMajorBadge = ({title}: {title: string}) => ( + + React 19 + +); + +const RSCBadge = ({title}: {title: string}) => ( + + RSC + +); + const Blockquote = ({ children, ...props @@ -483,6 +511,10 @@ export const MDXComponents = { Note, Canary, CanaryBadge, + NextMajor, + NextMajorBadge, + RSC, + RSCBadge, PackageImport, ReadBlogPost, Recap, diff --git a/src/components/MDX/Sandpack/Preview.tsx b/src/components/MDX/Sandpack/Preview.tsx index 9669e5f4f..7d7cdc5a7 100644 --- a/src/components/MDX/Sandpack/Preview.tsx +++ b/src/components/MDX/Sandpack/Preview.tsx @@ -113,7 +113,7 @@ export function Preview({ /** * The spinner component transition might be longer than * the bundler loading, so we only show the spinner if - * it takes more than 1s to load the bundler. + * it takes more than 500s to load the bundler. */ timeout = setTimeout(() => { setShowLoading(true); diff --git a/src/components/MDX/Sandpack/template.ts b/src/components/MDX/Sandpack/template.ts index 9ead18a14..42f02f6a6 100644 --- a/src/components/MDX/Sandpack/template.ts +++ b/src/components/MDX/Sandpack/template.ts @@ -28,8 +28,8 @@ root.render( eject: 'react-scripts eject', }, dependencies: { - react: '^18.0.0', - 'react-dom': '^18.0.0', + react: '19.0.0-rc-3edc000d-20240926', + 'react-dom': '19.0.0-rc-3edc000d-20240926', 'react-scripts': '^5.0.0', }, }, diff --git a/src/components/MDX/TeamMember.tsx b/src/components/MDX/TeamMember.tsx index eaf74187e..e1b9198d8 100644 --- a/src/components/MDX/TeamMember.tsx +++ b/src/components/MDX/TeamMember.tsx @@ -6,6 +6,7 @@ import * as React from 'react'; import Image from 'next/image'; import {IconTwitter} from '../Icon/IconTwitter'; import {IconThreads} from '../Icon/IconThreads'; +import {IconBsky} from '../Icon/IconBsky'; import {IconGitHub} from '../Icon/IconGitHub'; import {ExternalLink} from '../ExternalLink'; import {H3} from './Heading'; @@ -19,6 +20,7 @@ interface TeamMemberProps { photo: string; twitter?: string; threads?: string; + bsky?: string; github?: string; personal?: string; } @@ -33,6 +35,7 @@ export function TeamMember({ github, twitter, threads, + bsky, personal, }: TeamMemberProps) { if (name == null || title == null || permalink == null || children == null) { @@ -62,11 +65,11 @@ export function TeamMember({ {title &&
{title}
} {children} -
+
{twitter && (
@@ -77,7 +80,7 @@ export function TeamMember({ {threads && (
@@ -85,6 +88,17 @@ export function TeamMember({
)} + {bsky && ( +
+ + + {bsky} + +
+ )} {github && (
- {name} {isPacked && '✔'} + {name} {isPacked && '✅'} ); } @@ -307,7 +307,7 @@ export default function PackingList() { function Item({ name, isPacked }) { return (
  • - {name} {isPacked ? '✔' : '❌'} + {name} {isPacked ? '✅' : '❌'}
  • ); } diff --git a/src/content/blog/2024/04/25/react-19-upgrade-guide.md b/src/content/blog/2024/04/25/react-19-upgrade-guide.md index f464df959..fbc4e378c 100644 --- a/src/content/blog/2024/04/25/react-19-upgrade-guide.md +++ b/src/content/blog/2024/04/25/react-19-upgrade-guide.md @@ -1,5 +1,5 @@ --- -title: "React 19 RC Upgrade Guide" +title: "React 19 Upgrade Guide" author: Ricky Hanlon date: 2024/04/25 description: The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible and we don't expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading apps and libraries to React 19. @@ -12,7 +12,7 @@ April 25, 2024 by [Ricky Hanlon](https://twitter.com/rickhanlonii) -The improvements added to React 19 RC require some breaking changes, but we've worked to make the upgrade as smooth as possible, and we don't expect the changes to impact most apps. +The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible, and we don't expect the changes to impact most apps. @@ -38,7 +38,7 @@ In this post, we will guide you through the steps for upgrading to React 19: - [TypeScript changes](#typescript-changes) - [Changelog](#changelog) -If you'd like to help us test React 19, follow the steps in this upgrade guide and [report any issues](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D) you encounter. For a list of new features added to React 19, see the [React 19 release post](/blog/2024/04/25/react-19). +If you'd like to help us test React 19, follow the steps in this upgrade guide and [report any issues](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D) you encounter. For a list of new features added to React 19, see the [React 19 release post](/blog/2024/12/05/react-19). --- ## Installing {/*installing*/} @@ -70,28 +70,23 @@ We expect most apps will not be affected since the transform is enabled in most To install the latest version of React and React DOM: ```bash -npm install --save-exact react@rc react-dom@rc +npm install --save-exact react@^19.0.0 react-dom@^19.0.0 ``` Or, if you're using Yarn: ```bash -yarn add --exact react@rc react-dom@rc +yarn add --exact react@^19.0.0 react-dom@^19.0.0 ``` -If you're using TypeScript, you also need to update the types. Once React 19 is released as stable, you can install the types as usual from `@types/react` and `@types/react-dom`. Until the stable release, the types are available in different packages which need to be enforced in your `package.json`: +If you're using TypeScript, you also need to update the types. +```bash +npm install --save-exact @types/react@^19.0.0 @types/react-dom@^19.0.0 +``` -```json -{ - "dependencies": { - "@types/react": "npm:types-react@rc", - "@types/react-dom": "npm:types-react-dom@rc" - }, - "overrides": { - "@types/react": "npm:types-react@rc", - "@types/react-dom": "npm:types-react-dom@rc" - } -} +Or, if you're using Yarn: +```bash +yarn add --exact @types/react@^19.0.0 @types/react-dom@^19.0.0 ``` We're also including a codemod for the most common replacements. See [TypeScript changes](#typescript-changes) below. @@ -118,7 +113,7 @@ This will run the following codemods from `react-codemod`: - [`replace-string-ref`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-string-ref) - [`replace-act-import`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-act-import) - [`replace-use-form-state`](https://github.com/reactjs/react-codemod?tab=readme-ov-file#replace-use-form-state) -- [`prop-types-typescript`](TODO) +- [`prop-types-typescript`](https://codemod.com/registry/react-prop-types-typescript) This does not include the TypeScript changes. See [TypeScript changes](#typescript-changes) below. @@ -353,7 +348,7 @@ npm install react-shallow-renderer --save-dev ##### Please reconsider shallow rendering {/*please-reconsider-shallow-rendering*/} -Shallow rendering depends on React internals and can block you from future upgrades. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://callstack.github.io/react-native-testing-library/docs/getting-started). +Shallow rendering depends on React internals and can block you from future upgrades. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro). @@ -524,7 +519,7 @@ We are deprecating `react-test-renderer` because it implements its own renderer The test renderer was created before there were more viable testing strategies available like [React Testing Library](https://testing-library.com), and we now recommend using a modern testing library instead. -In React 19, `react-test-renderer` logs a deprecation warning, and has switched to concurrent rendering. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://callstack.github.io/react-native-testing-library/docs/getting-started) for a modern and well supported testing experience. +In React 19, `react-test-renderer` logs a deprecation warning, and has switched to concurrent rendering. We recommend migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/) or [@testing-library/react-native](https://testing-library.com/docs/react-native-testing-library/intro) for a modern and well supported testing experience. ## Notable changes {/*notable-changes*/} @@ -536,6 +531,24 @@ When double rendering in Strict Mode in development, `useMemo` and `useCallback` As with all Strict Mode behaviors, these features are designed to proactively surface bugs in your components during development so you can fix them before they are shipped to production. For example, during development, Strict Mode will double-invoke ref callback functions on initial mount, to simulate what happens when a mounted component is replaced by a Suspense fallback. +### Improvements to Suspense {/*improvements-to-suspense*/} + +In React 19, when a component suspends, React will immediately commit the fallback of the nearest Suspense boundary without waiting for the entire sibling tree to render. After the fallback commits, React schedules another render for the suspended siblings to "pre-warm" lazy requests in the rest of the tree: + + + +Previously, when a component suspended, the suspended siblings were rendered and then the fallback was committed. + + + + + +In React 19, when a component suspends, the fallback is committed and then the suspended siblings are rendered. + + + +This change means Suspense fallbacks display faster, while still warming lazy requests in the suspended tree. + ### UMD builds removed {/*umd-builds-removed*/} UMD was widely used in the past as a convenient way to load React without a build step. Now, there are modern alternatives for loading modules as scripts in HTML documents. Starting with React 19, React will no longer produce UMD builds to reduce the complexity of its testing and release process. @@ -717,12 +730,12 @@ const reducer = (state: State, action: Action) => state; ### Other breaking changes {/*other-breaking-changes*/} -- **react-dom**: Error for javascript URLs in src/href [#26507](https://github.com/facebook/react/pull/26507) +- **react-dom**: Error for javascript URLs in `src` and `href` [#26507](https://github.com/facebook/react/pull/26507) - **react-dom**: Remove `errorInfo.digest` from `onRecoverableError` [#28222](https://github.com/facebook/react/pull/28222) - **react-dom**: Remove `unstable_flushControlled` [#26397](https://github.com/facebook/react/pull/26397) - **react-dom**: Remove `unstable_createEventHandle` [#28271](https://github.com/facebook/react/pull/28271) - **react-dom**: Remove `unstable_renderSubtreeIntoContainer` [#28271](https://github.com/facebook/react/pull/28271) -- **react-dom**: Remove `unstable_runWithPrioirty` [#28271](https://github.com/facebook/react/pull/28271) +- **react-dom**: Remove `unstable_runWithPriority` [#28271](https://github.com/facebook/react/pull/28271) - **react-is**: Remove deprecated methods from `react-is` [28224](https://github.com/facebook/react/pull/28224) ### Other notable changes {/*other-notable-changes*/} @@ -734,7 +747,7 @@ const reducer = (state: State, action: Action) => state; - **react-dom**: Remove layout effect warning during SSR [#26395](https://github.com/facebook/react/pull/26395) - **react-dom**: Warn and don’t set empty string for src/href (except anchor tags) [#28124](https://github.com/facebook/react/pull/28124) -We'll publish the full changelog with the stable release of React 19. +For a full list of changes, please see the [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md#1900-december-5-2024). --- diff --git a/src/content/blog/2024/05/22/react-conf-2024-recap.md b/src/content/blog/2024/05/22/react-conf-2024-recap.md index 96417fd8b..bc77f4bbb 100644 --- a/src/content/blog/2024/05/22/react-conf-2024-recap.md +++ b/src/content/blog/2024/05/22/react-conf-2024-recap.md @@ -17,7 +17,7 @@ Last week we hosted React Conf 2024, a two-day conference in Henderson, Nevada w --- -At React Conf 2024, we announced the [React 19 RC](/blog/2024/04/25/react-19), the [React Native New Architecture Beta](https://github.com/reactwg/react-native-new-architecture/discussions/189), and an experimental release of the [React Compiler](/learn/react-compiler). The community also took the stage to announce [React Router v7](https://remix.run/blog/merging-remix-and-react-router), [Universal Server Components](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=20765s) in Expo Router, React Server Components in [RedwoodJS](https://redwoodjs.com/blog/rsc-now-in-redwoodjs), and much more. +At React Conf 2024, we announced the [React 19 RC](/blog/2024/12/05/react-19), the [React Native New Architecture Beta](https://github.com/reactwg/react-native-new-architecture/discussions/189), and an experimental release of the [React Compiler](/learn/react-compiler). The community also took the stage to announce [React Router v7](https://remix.run/blog/merging-remix-and-react-router), [Universal Server Components](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=20765s) in Expo Router, React Server Components in [RedwoodJS](https://redwoodjs.com/blog/rsc-now-in-redwoodjs), and much more. The entire [day 1](https://www.youtube.com/watch?v=T8TZQ6k4SLE) and [day 2](https://www.youtube.com/watch?v=0ckOUBiuxVY) streams are available online. In this post, we'll summarize the talks and announcements from the event. @@ -36,7 +36,7 @@ For more, check out these talks from the community later in the conference: - [RedwoodJS, now with React Server Components](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=26815s) by [Amy Dutton](https://twitter.com/selfteachme) - [Introducing Universal React Server Components in Expo Router](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=20765s) by [Evan Bacon](https://twitter.com/Baconbrix) -Next in the keynote, [Josh Story](https://twitter.com/joshcstory) and [Andrew Clark](https://twitter.com/acdlite) shared new features coming in React 19, and announced the React 19 RC which is ready for testing in production. Check out all the features in the [React 19 release post](/blog/2024/04/25/react-19), and see these talks for deep dives on the new features: +Next in the keynote, [Josh Story](https://twitter.com/joshcstory) and [Andrew Clark](https://twitter.com/acdlite) shared new features coming in React 19, and announced the React 19 RC which is ready for testing in production. Check out all the features in the [React 19 release post](/blog/2024/12/05/react-19), and see these talks for deep dives on the new features: - [What's new in React 19](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=8880s) by [Lydia Hallie](https://twitter.com/lydiahallie) - [React Unpacked: A Roadmap to React 19](https://www.youtube.com/watch?v=T8TZQ6k4SLE&t=10112s) by [Sam Selikoff](https://twitter.com/samselikoff) diff --git a/src/content/blog/2024/10/21/react-compiler-beta-release.md b/src/content/blog/2024/10/21/react-compiler-beta-release.md new file mode 100644 index 000000000..f5a870b22 --- /dev/null +++ b/src/content/blog/2024/10/21/react-compiler-beta-release.md @@ -0,0 +1,126 @@ +--- +title: "React Compiler Beta Release" +author: Lauren Tan +date: 2024/10/21 +description: At React Conf 2024, we announced the experimental release of React Compiler, a build-time tool that optimizes your React app through automatic memoization. In this post, we want to share what's next for open source, and our progress on the compiler. + +--- + +October 21, 2024 by [Lauren Tan](https://twitter.com/potetotes). + +--- + + + +The React team is excited to share new updates: + + + +1. We're publishing React Compiler Beta today, so that early adopters and library maintainers can try it and provide feedback. +2. We're officially supporting React Compiler for apps on React 17+, through an optional `react-compiler-runtime` package. +3. We're opening up public membership of the [React Compiler Working Group](https://github.com/reactwg/react-compiler) to prepare the community for gradual adoption of the compiler. + +--- + +At [React Conf 2024](/blog/2024/05/22/react-conf-2024-recap), we announced the experimental release of React Compiler, a build-time tool that optimizes your React app through automatic memoization. [You can find an introduction to React Compiler here](/learn/react-compiler). + +Since the first release, we've fixed numerous bugs reported by the React community, received several high quality bug fixes and contributions[^1] to the compiler, made the compiler more resilient to the broad diversity of JavaScript patterns, and have continued to roll out the compiler more widely at Meta. + +In this post, we want to share what's next for React Compiler. + +## Try React Compiler Beta today {/*try-react-compiler-beta-today*/} + +At [React India 2024](https://www.youtube.com/watch?v=qd5yk2gxbtg), we shared an update on React Compiler. Today, we are excited to announce a new Beta release of React Compiler and ESLint plugin. New betas are published to npm using the `@beta` tag. + +To install React Compiler Beta: + + +npm install -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta + + +Or, if you're using Yarn: + + +yarn add -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta + + +You can watch [Sathya Gunasekaran's](https://twitter.com/_gsathya) talk at React India here: + + + +## We recommend everyone use the React Compiler linter today {/*we-recommend-everyone-use-the-react-compiler-linter-today*/} + +React Compiler’s ESLint plugin helps developers proactively identify and correct [Rules of React](/reference/rules) violations. **We strongly recommend everyone use the linter today**. The linter does not require that you have the compiler installed, so you can use it independently, even if you are not ready to try out the compiler. + +To install the linter only: + + +npm install -D eslint-plugin-react-compiler@beta + + +Or, if you're using Yarn: + + +yarn add -D eslint-plugin-react-compiler@beta + + +After installation you can enable the linter by [adding it to your ESLint config](/learn/react-compiler#installing-eslint-plugin-react-compiler). Using the linter helps identify Rules of React breakages, making it easier to adopt the compiler when it's fully released. + +## Backwards Compatibility {/*backwards-compatibility*/} + +React Compiler produces code that depends on runtime APIs added in React 19, but we've since added support for the compiler to also work with React 17 and 18. If you are not on React 19 yet, in the Beta release you can now try out React Compiler by specifying a minimum `target` in your compiler config, and adding `react-compiler-runtime` as a dependency. [You can find docs on this here](/learn/react-compiler#using-react-compiler-with-react-17-or-18). + +## Using React Compiler in libraries {/*using-react-compiler-in-libraries*/} + +Our initial release was focused on identifying major issues with using the compiler in applications. We've gotten great feedback and have substantially improved the compiler since then. We're now ready for broad feedback from the community, and for library authors to try out the compiler to improve performance and the developer experience of maintaining your library. + +React Compiler can also be used to compile libraries. Because React Compiler needs to run on the original source code prior to any code transformations, it is not possible for an application's build pipeline to compile the libraries they use. Hence, our recommendation is for library maintainers to independently compile and test their libraries with the compiler, and ship compiled code to npm. + +Because your code is pre-compiled, users of your library will not need to have the compiler enabled in order to benefit from the automatic memoization applied to your library. If your library targets apps not yet on React 19, specify a minimum `target` and add `react-compiler-runtime` as a direct dependency. The runtime package will use the correct implementation of APIs depending on the application's version, and polyfill the missing APIs if necessary. + +[You can find more docs on this here.](/learn/react-compiler#using-the-compiler-on-libraries) + +## Opening up React Compiler Working Group to everyone {/*opening-up-react-compiler-working-group-to-everyone*/} + +We previously announced the invite-only [React Compiler Working Group](https://github.com/reactwg/react-compiler) at React Conf to provide feedback, ask questions, and collaborate on the compiler's experimental release. + +From today, together with the Beta release of React Compiler, we are opening up Working Group membership to everyone. The goal of the React Compiler Working Group is to prepare the ecosystem for a smooth, gradual adoption of React Compiler by existing applications and libraries. Please continue to file bug reports in the [React repo](https://github.com/facebook/react), but please leave feedback, ask questions, or share ideas in the [Working Group discussion forum](https://github.com/reactwg/react-compiler/discussions). + +The core team will also use the discussions repo to share our research findings. As the Stable Release gets closer, any important information will also be posted on this forum. + +## React Compiler at Meta {/*react-compiler-at-meta*/} + +At [React Conf](/blog/2024/05/22/react-conf-2024-recap), we shared that our rollout of the compiler on Quest Store and Instagram were successful. Since then, we've deployed React Compiler across several more major web apps at Meta, including [Facebook](https://www.facebook.com) and [Threads](https://www.threads.net). That means if you've used any of these apps recently, you may have had your experience powered by the compiler. We were able to onboard these apps onto the compiler with few code changes required, in a monorepo with more than 100,000 React components. + +We've seen notable performance improvements across all of these apps. As we've rolled out, we're continuing to see results on the order of [the wins we shared previously at ReactConf](https://youtu.be/lyEKhv8-3n0?t=3223). These apps have already been heavily hand tuned and optimized by Meta engineers and React experts over the years, so even improvements on the order of a few percent are a huge win for us. + +We also expected developer productivity wins from React Compiler. To measure this, we collaborated with our data science partners at Meta[^2] to conduct a thorough statistical analysis of the impact of manual memoization on productivity. Before rolling out the compiler at Meta, we discovered that only about 8% of React pull requests used manual memoization and that these pull requests took 31-46% longer to author[^3]. This confirmed our intuition that manual memoization introduces cognitive overhead, and we anticipate that React Compiler will lead to more efficient code authoring and review. Notably, React Compiler also ensures that *all* code is memoized by default, not just the (in our case) 8% where developers explicitly apply memoization. + +## Roadmap to Stable {/*roadmap-to-stable*/} + +*This is not a final roadmap, and is subject to change.* + +We intend to ship a Release Candidate of the compiler in the near future following the Beta release, when the majority of apps and libraries that follow the Rules of React have been proven to work well with the compiler. After a period of final feedback from the community, we plan on a Stable Release for the compiler. The Stable Release will mark the beginning of a new foundation for React, and all apps and libraries will be strongly recommended to use the compiler and ESLint plugin. + +* ✅ Experimental: Released at React Conf 2024, primarily for feedback from early adopters. +* ✅ Public Beta: Available today, for feedback from the wider community. +* 🚧 Release Candidate (RC): React Compiler works for the majority of rule-following apps and libraries without issue. +* 🚧 General Availability: After final feedback period from the community. + +These releases also include the compiler's ESLint plugin, which surfaces diagnostics statically analyzed by the compiler. We plan to combine the existing eslint-plugin-react-hooks plugin with the compiler's ESLint plugin, so only one plugin needs to be installed. + +Post-Stable, we plan to add more compiler optimizations and improvements. This includes both continual improvements to automatic memoization, and new optimizations altogether, with minimal to no change of product code. Upgrading to each new release of the compiler is aimed to be straightforward, and each upgrade will continue to improve performance and add better handling of diverse JavaScript and React patterns. + +Throughout this process, we also plan to prototype an IDE extension for React. It is still very early in research, so we expect to be able to share more of our findings with you in a future React Labs blog post. + +--- + +Thanks to [Sathya Gunasekaran](https://twitter.com/_gsathya), [Joe Savona](https://twitter.com/en_JS), [Ricky Hanlon](https://twitter.com/rickhanlonii), [Alex Taylor](https://github.com/alexmckenley), [Jason Bonta](https://twitter.com/someextent), and [Eli White](https://twitter.com/Eli_White) for reviewing and editing this post. + +--- + +[^1]: Thanks [@nikeee](https://github.com/facebook/react/pulls?q=is%3Apr+author%3Anikeee), [@henryqdineen](https://github.com/facebook/react/pulls?q=is%3Apr+author%3Ahenryqdineen), [@TrickyPi](https://github.com/facebook/react/pulls?q=is%3Apr+author%3ATrickyPi), and several others for their contributions to the compiler. + +[^2]: Thanks [Vaishali Garg](https://www.linkedin.com/in/vaishaligarg09) for leading this study on React Compiler at Meta, and for reviewing this post. + +[^3]: After controlling on author tenure, diff length/complexity, and other potential confounding factors. \ No newline at end of file diff --git a/src/content/blog/2024/04/25/react-19.md b/src/content/blog/2024/12/05/react-19.md similarity index 92% rename from src/content/blog/2024/04/25/react-19.md rename to src/content/blog/2024/12/05/react-19.md index 1b19c3546..62a6ce464 100644 --- a/src/content/blog/2024/04/25/react-19.md +++ b/src/content/blog/2024/12/05/react-19.md @@ -1,21 +1,33 @@ --- -title: "React 19 RC" +title: "React v19" author: The React Team -date: 2024/04/25 -description: React 19 RC is now available on npm! In this post, we'll give an overview of the new features in React 19, and how you can adopt them. +date: 2024/12/05 +description: React 19 is now available on npm! In this post, we'll give an overview of the new features in React 19, and how you can adopt them. --- -April 25, 2024 by [The React Team](/community/team) +December 05, 2024 by [The React Team](/community/team) --- + + +### React 19 is now stable! {/*react-19-is-now-stable*/} + +Additions since this post was originally shared with the React 19 RC in April: + +- **Pre-warming for suspended trees**: see [Improvements to Suspense](/blog/2024/04/25/react-19-upgrade-guide#improvements-to-suspense). +- **React DOM static APIs**: see [New React DOM Static APIs](#new-react-dom-static-apis). + +_The date for this post has been updated to reflect the stable release date._ + + -React 19 RC is now available on npm! +React v19 is now available on npm! -In our [React 19 RC Upgrade Guide](/blog/2024/04/25/react-19-upgrade-guide), we shared step-by-step instructions for upgrading your app to React 19. In this post, we'll give an overview of the new features in React 19, and how you can adopt them. +In our [React 19 Upgrade Guide](/blog/2024/04/25/react-19-upgrade-guide), we shared step-by-step instructions for upgrading your app to React 19. In this post, we'll give an overview of the new features in React 19, and how you can adopt them. - [What's new in React 19](#whats-new-in-react-19) - [Improvements in React 19](#improvements-in-react-19) @@ -312,6 +324,30 @@ The `use` API can only be called in render, similar to hooks. Unlike hooks, `use For more information, see the docs for [`use`](/reference/react/use). +## New React DOM Static APIs {/*new-react-dom-static-apis*/} + +We've added two new APIs to `react-dom/static` for static site generation: +- [`prerender`](/reference/react-dom/static/prerender) +- [`prerenderToNodeStream`](/reference/react-dom/static/prerenderToNodeStream) + +These new APIs improve on `renderToString` by waiting for data to load for static HTML generation. They are designed to work with streaming environments like Node.js Streams and Web Streams. For example, in a Web Stream environment, you can prerender a React tree to static HTML with `prerender`: + +```js +import { prerender } from 'react-dom/static'; + +async function handler(request) { + const {prelude} = await prerender(, { + bootstrapScripts: ['/main.js'] + }); + return new Response(prelude, { + headers: { 'content-type': 'text/html' }, + }); +} +``` + +Prerender APIs will wait for all data to load before returning the static HTML stream. Streams can be converted to strings, or sent with a streaming response. They do not support streaming content as it loads, which is supported by the existing [React DOM server rendering APIs](/reference/react-dom/server). + +For more information, see [React DOM Static APIs](/reference/react-dom/static). ## React Server Components {/*react-server-components*/} @@ -326,7 +362,7 @@ React 19 includes all of the React Server Components features included from the #### How do I build support for Server Components? {/*how-do-i-build-support-for-server-components*/} -While React Server Components in React 19 are stable and will not break between major versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x. +While React Server Components in React 19 are stable and will not break between minor versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x. To support React Server Components as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement React Server Components in the future. @@ -771,5 +807,4 @@ Thanks to [Joey Arhar](https://github.com/josepharhar) for driving the design an #### How to upgrade {/*how-to-upgrade*/} See the [React 19 Upgrade Guide](/blog/2024/04/25/react-19-upgrade-guide) for step-by-step instructions and a full list of breaking and notable changes. - - +_Note: this post was originally published 04/25/2024 and has been updated to 12/05/2024 with the stable release._ diff --git a/src/content/blog/index.md b/src/content/blog/index.md index 4a1a165a3..cc50b83c0 100644 --- a/src/content/blog/index.md +++ b/src/content/blog/index.md @@ -10,19 +10,25 @@ This blog is the official source for the updates from the React team. Anything i
    - + -Last week we hosted React Conf 2024, a two-day conference in Henderson, Nevada where 700+ attendees gathered in-person to discuss the latest in UI engineering. This was our first in-person conference since 2019, and we were thrilled to be able to bring the community together again ... +In the React 19 Upgrade Guide, we shared step-by-step instructions for upgrading your app to React 19. In this post, we'll give an overview of the new features in React 19, and how you can adopt them ... + + + + + +We announced an experimental release of React Compiler at React Conf 2024. We've made a lot of progress since then, and in this post we want to share what's next for React Compiler ... - + -In the React 19 RC Upgrade Guide, we shared step-by-step instructions for upgrading your app to React 19. In this post, we'll give an overview of the new features in React 19, and how you can adopt them ... +Last week we hosted React Conf 2024, a two-day conference in Henderson, Nevada where 700+ attendees gathered in-person to discuss the latest in UI engineering. This was our first in-person conference since 2019, and we were thrilled to be able to bring the community together again ... - + The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible, and we don't expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading libraries to React 19 ... diff --git a/src/content/community/acknowledgements.md b/src/content/community/acknowledgements.md index aeb0787ef..760076d83 100644 --- a/src/content/community/acknowledgements.md +++ b/src/content/community/acknowledgements.md @@ -4,7 +4,7 @@ title: Acknowledgements -React was originally created by [Jordan Walke.](https://github.com/jordwalke) Today, React has a [dedicated full-time team working on it](/community/team), as well as over a thousand [open source contributors.](https://github.com/facebook/react/blob/main/AUTHORS) +React was originally created by [Jordan Walke.](https://github.com/jordwalke) Today, React has a [dedicated full-time team working on it](/community/team), as well as over a thousand [open source contributors.](https://github.com/facebook/react/graphs/contributors) @@ -59,7 +59,7 @@ We'd like to recognize a few people who have made significant contributions to R This list is not exhaustive. -We'd like to give special thanks to [Tom Occhino](https://github.com/tomocchino) and [Adam Wolff](https://github.com/wolffiex) for their guidance and support over the years. We are also thankful to all the volunteers who [translated React into other languages.](https://translations.reactjs.org/) +We'd like to give special thanks to [Tom Occhino](https://github.com/tomocchino) and [Adam Wolff](https://github.com/wolffiex) for their guidance and support over the years. We are also thankful to all the volunteers who [translated React into other languages.](https://translations.react.dev/) ## Additional Thanks {/*additional-thanks*/} diff --git a/src/content/community/conferences.md b/src/content/community/conferences.md index 5070fbc41..6b95c64c6 100644 --- a/src/content/community/conferences.md +++ b/src/content/community/conferences.md @@ -10,57 +10,93 @@ Do you know of a local React.js conference? Add it here! (Please keep the list c ## Upcoming Conferences {/*upcoming-conferences*/} -### React Nexus 2024 {/*react-nexus-2024*/} -July 04 & 05, 2024. Bangalore, India (In-person event) +### React Day Berlin 2024 {/*react-day-berlin-2024*/} +December 13 & 16, 2024. In-person in Berlin, Germany + remote (hybrid event) -[Website](https://reactnexus.com/) - [Twitter](https://twitter.com/ReactNexus) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in) +[Website](https://reactday.berlin/) - [Twitter](https://x.com/reactdayberlin) -### Chain React 2024 {/*chain-react-2024*/} -July 17-19, 2024. In-person in Portland, OR, USA +### App.js Conf 2025 {/*appjs-conf-2025*/} +May 28 - 30, 2025. In-person in Kraków, Poland + remote -[Website](https://chainreactconf.com) - [Twitter](https://twitter.com/ChainReactConf) +[Website](https://appjs.co) - [Twitter](https://twitter.com/appjsconf) -### The Geek Conf 2024 {/*the-geek-conf-2024*/} -July 25, 2024. In-person in Berlin, Germany + remote (hybrid event) +### React Summit 2025 {/*react-summit-2025*/} +June 13 - 17, 2025. In-person in Amsterdam, Netherlands + remote (hybrid event) -[Website](https://thegeekconf.com) - [Twitter](https://twitter.com/thegeekconf) +[Website](https://reactsummit.com/) - [Twitter](https://x.com/reactsummit) -### React Rally 2024 🐙 {/*react-rally-2024*/} -August 12-13, 2024. Park City, UT, USA +## Past Conferences {/*past-conferences*/} -[Website](https://reactrally.com) - [Twitter](https://twitter.com/ReactRally) - [YouTube](https://www.youtube.com/channel/UCXBhQ05nu3L1abBUGeQ0ahw) +### React Africa 2024 {/*react-africa-2024*/} +November 29, 2024. In-person in Casablanca, Morocco (hybrid event) -### React Universe Conf 2024 {/*react-universe-conf-2024*/} -September 5-6, 2024. Wrocław, Poland. +[Website](https://react-africa.com/) - [Twitter](https://x.com/BeJS_) -[Website](https://www.reactuniverseconf.com/) - [Twitter](https://twitter.com/react_native_eu) - [LinkedIn](https://www.linkedin.com/events/reactuniverseconf7163919537074118657/) +### React Summit US 2024 {/*react-summit-us-2024*/} +November 19 & 22, 2024. In-person in New York, USA + online (hybrid event) -### React Alicante 2024 {/*react-alicante-2024*/} -September 19-21, 2024. Alicante, Spain. +[Website](https://reactsummit.us/) - [Twitter](https://twitter.com/reactsummit) - [Videos](https://portal.gitnation.org/) -[Website](https://reactalicante.es/) - [Twitter](https://twitter.com/ReactAlicante) - [YouTube](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w) +### React Native London Conf 2024 {/*react-native-london-2024*/} +November 14 & 15, 2024. In-person in London, UK -### RenderCon Kenya 2024 {/*rendercon-kenya-2024*/} -October 04 - 05, 2024. Nairobi, Kenya +[Website](https://reactnativelondon.co.uk/) - [Twitter](https://x.com/RNLConf) -[Website](https://rendercon.org/) - [Twitter](https://twitter.com/renderconke) - [LinkedIn](https://www.linkedin.com/company/renderconke/) - [YouTube](https://www.youtube.com/channel/UC0bCcG8gHUL4njDOpQGcMIA) +### React Advanced London 2024 {/*react-advanced-london-2024*/} +October 25 & 28, 2024. In-person in London, UK + online (hybrid event) -### React India 2024 {/*react-india-2024*/} -October 17 - 19, 2024. In-person in Goa, India (hybrid event) + Oct 15 2024 - remote day +[Website](https://reactadvanced.com/) - [Twitter](https://x.com/reactadvanced) -[Website](https://www.reactindia.io) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia) - [Youtube](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w) +### reactjsday 2024 {/*reactjsday-2024*/} +October 25, 2024. In-person in Verona, Italy + online (hybrid event) + +[Website](https://2024.reactjsday.it/) - [Twitter](https://x.com/reactjsday) - [Facebook](https://www.facebook.com/GrUSP/) - [YouTube](https://www.youtube.com/c/grusp) ### React Brussels 2024 {/*react-brussels-2024*/} October 18, 2024. In-person in Brussels, Belgium (hybrid event) [Website](https://www.react.brussels/) - [Twitter](https://x.com/BrusselsReact) -### React Africa 2024 {/*react-africa-2024*/} -November 29, 2024. In-person in Casablanca, Morocco (hybrid event) +### React India 2024 {/*react-india-2024*/} +October 17 - 19, 2024. In-person in Goa, India (hybrid event) + Oct 15 2024 - remote day -[Website](https://react-africa.com/) - [Twitter](https://x.com/BeJS_) +[Website](https://www.reactindia.io) - [Twitter](https://twitter.com/react_india) - [Facebook](https://www.facebook.com/ReactJSIndia) - [Youtube](https://www.youtube.com/channel/UCaFbHCBkPvVv1bWs_jwYt3w) -## Past Conferences {/*past-conferences*/} +### RenderCon Kenya 2024 {/*rendercon-kenya-2024*/} +October 04 - 05, 2024. Nairobi, Kenya + +[Website](https://rendercon.org/) - [Twitter](https://twitter.com/renderconke) - [LinkedIn](https://www.linkedin.com/company/renderconke/) - [YouTube](https://www.youtube.com/channel/UC0bCcG8gHUL4njDOpQGcMIA) + +### React Alicante 2024 {/*react-alicante-2024*/} +September 19-21, 2024. Alicante, Spain. + +[Website](https://reactalicante.es/) - [Twitter](https://twitter.com/ReactAlicante) - [YouTube](https://www.youtube.com/channel/UCaSdUaITU1Cz6PvC97A7e0w) + +### React Universe Conf 2024 {/*react-universe-conf-2024*/} +September 5-6, 2024. Wrocław, Poland. + +[Website](https://www.reactuniverseconf.com/) - [Twitter](https://twitter.com/react_native_eu) - [LinkedIn](https://www.linkedin.com/events/reactuniverseconf7163919537074118657/) + + +### React Rally 2024 🐙 {/*react-rally-2024*/} +August 12-13, 2024. Park City, UT, USA + +[Website](https://reactrally.com) - [Twitter](https://twitter.com/ReactRally) - [YouTube](https://www.youtube.com/channel/UCXBhQ05nu3L1abBUGeQ0ahw) + +### The Geek Conf 2024 {/*the-geek-conf-2024*/} +July 25, 2024. In-person in Berlin, Germany + remote (hybrid event) + +[Website](https://thegeekconf.com) - [Twitter](https://twitter.com/thegeekconf) + +### Chain React 2024 {/*chain-react-2024*/} +July 17-19, 2024. In-person in Portland, OR, USA + +[Website](https://chainreactconf.com) - [Twitter](https://twitter.com/ChainReactConf) + +### React Nexus 2024 {/*react-nexus-2024*/} +July 04 & 05, 2024. Bangalore, India (In-person event) + +[Website](https://reactnexus.com/) - [Twitter](https://twitter.com/ReactNexus) - [Linkedin](https://www.linkedin.com/company/react-nexus) - [YouTube](https://www.youtube.com/reactify_in) ### React Summit 2024 {/*react-summit-2024*/} June 14 & 18, 2024. In-person in Amsterdam, Netherlands + remote (hybrid event) diff --git a/src/content/community/meetups.md b/src/content/community/meetups.md index d8887c3de..14097aa4d 100644 --- a/src/content/community/meetups.md +++ b/src/content/community/meetups.md @@ -30,15 +30,8 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Belo Horizonte](https://www.meetup.com/reactbh/) * [Curitiba](https://www.meetup.com/pt-br/ReactJS-CWB/) * [Florianópolis](https://www.meetup.com/pt-br/ReactJS-Floripa/) -* [Goiânia](https://www.meetup.com/pt-br/React-Goiania/) * [Joinville](https://www.meetup.com/pt-BR/React-Joinville/) -* [Juiz de Fora](https://www.meetup.com/pt-br/React-Juiz-de-Fora/) -* [Maringá](https://www.meetup.com/pt-BR/React-Maringa/) -* [Porto Alegre](https://www.meetup.com/pt-BR/React-Porto-Alegre/) -* [Rio de Janeiro](https://www.meetup.com/pt-BR/React-Rio-de-Janeiro/) -* [Salvador](https://www.meetup.com/pt-BR/ReactSSA) * [São Paulo](https://www.meetup.com/pt-BR/ReactJS-SP/) -* [Vila Velha](https://www.meetup.com/pt-BR/React-ES/) ## Bolivia {/*bolivia*/} * [Bolivia](https://www.meetup.com/ReactBolivia/) @@ -51,24 +44,13 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Saskatoon, SK](https://www.meetup.com/saskatoon-react-meetup/) * [Toronto, ON](https://www.meetup.com/Toronto-React-Native/events/) -## Chile {/*chile*/} -* [Santiago](https://www.meetup.com/es-ES/react-santiago/) - -## China {/*china*/} -* [Beijing](https://www.meetup.com/Beijing-ReactJS-Meetup/) - ## Colombia {/*colombia*/} -* [Bogotá](https://www.meetup.com/meetup-group-iHIeHykY/) * [Medellin](https://www.meetup.com/React-Medellin/) -* [Cali](https://www.meetup.com/reactcali/) ## Denmark {/*denmark*/} * [Aalborg](https://www.meetup.com/Aalborg-React-React-Native-Meetup/) * [Aarhus](https://www.meetup.com/Aarhus-ReactJS-Meetup/) -## Egypt {/*egypt*/} -* [Cairo](https://www.meetup.com/react-cairo/) - ## England (UK) {/*england-uk*/} * [Manchester](https://www.meetup.com/Manchester-React-User-Group/) * [React.JS Girls London](https://www.meetup.com/ReactJS-Girls-London/) @@ -76,7 +58,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [React Native London](https://guild.host/RNLDN) ## France {/*france*/} -* [Nantes](https://www.meetup.com/React-Nantes/) * [Lille](https://www.meetup.com/ReactBeerLille/) * [Paris](https://www.meetup.com/ReactJS-Paris/) @@ -93,9 +74,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Athens](https://www.meetup.com/React-To-React-Athens-MeetUp/) * [Thessaloniki](https://www.meetup.com/Thessaloniki-ReactJS-Meetup/) -## Hungary {/*hungary*/} -* [Budapest](https://www.meetup.com/React-Budapest/) - ## India {/*india*/} * [Ahmedabad](https://www.meetup.com/react-ahmedabad/) * [Bangalore (React)](https://www.meetup.com/ReactJS-Bangalore/) @@ -117,6 +95,9 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet ## Italy {/*italy*/} * [Milan](https://www.meetup.com/React-JS-Milano/) +## Japan {/*japan*/} +* [Osaka](https://react-osaka.connpass.com/) + ## Kenya {/*kenya*/} * [Nairobi - Reactdevske](https://kommunity.com/reactjs-developer-community-kenya-reactdevske) @@ -138,12 +119,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Karachi](https://www.facebook.com/groups/902678696597634/) * [Lahore](https://www.facebook.com/groups/ReactjsLahore/) -## Panama {/*panama*/} -* [Panama](https://www.meetup.com/React-Panama/) - -## Peru {/*peru*/} -* [Lima](https://www.meetup.com/ReactJS-Peru/) - ## Philippines {/*philippines*/} * [Manila](https://www.meetup.com/reactjs-developers-manila/) * [Manila - ReactJS PH](https://www.meetup.com/ReactJS-Philippines/) @@ -160,7 +135,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet ## Spain {/*spain*/} * [Barcelona](https://www.meetup.com/ReactJS-Barcelona/) -* [Canarias](https://www.meetup.com/React-Canarias/) ## Sweden {/*sweden*/} * [Goteborg](https://www.meetup.com/ReactJS-Goteborg/) @@ -176,7 +150,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Kyiv](https://www.meetup.com/Kyiv-ReactJS-Meetup) ## US {/*us*/} -* [Ann Arbor, MI - ReactJS](https://www.meetup.com/AnnArbor-jsx/) * [Atlanta, GA - ReactJS](https://www.meetup.com/React-ATL/) * [Austin, TX - ReactJS](https://www.meetup.com/ReactJS-Austin-Meetup/) * [Boston, MA - ReactJS](https://www.meetup.com/ReactJS-Boston/) @@ -187,7 +160,6 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Cleveland, OH - ReactJS](https://www.meetup.com/Cleveland-React/) * [Columbus, OH - ReactJS](https://www.meetup.com/ReactJS-Columbus-meetup/) * [Dallas, TX - ReactJS](https://www.meetup.com/ReactDallas/) -* [Dallas, TX - [Remote] React JS](https://www.meetup.com/React-JS-Group/) * [Detroit, MI - Detroit React User Group](https://www.meetup.com/Detroit-React-User-Group/) * [Indianapolis, IN - React.Indy](https://www.meetup.com/React-Indy) * [Irvine, CA - ReactJS](https://www.meetup.com/ReactJS-OC/) @@ -197,27 +169,19 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Los Angeles, CA - ReactJS](https://www.meetup.com/socal-react/) * [Los Angeles, CA - React Native](https://www.meetup.com/React-Native-Los-Angeles/) * [Miami, FL - ReactJS](https://www.meetup.com/React-Miami/) -* [Nashville, TN - ReactJS](https://www.meetup.com/NashReact-Meetup/) * [New York, NY - ReactJS](https://www.meetup.com/NYC-Javascript-React-Group/) * [New York, NY - React Ladies](https://www.meetup.com/React-Ladies/) * [New York, NY - React Native](https://www.meetup.com/React-Native-NYC/) * [New York, NY - useReactNYC](https://www.meetup.com/useReactNYC/) * [New York, NY - React.NYC](https://guild.host/react-nyc) -* [Omaha, NE - ReactJS/React Native](https://www.meetup.com/omaha-react-meetup-group/) * [Palo Alto, CA - React Native](https://www.meetup.com/React-Native-Silicon-Valley/) -* [Philadelphia, PA - ReactJS](https://www.meetup.com/Reactadelphia/) * [Phoenix, AZ - ReactJS](https://www.meetup.com/ReactJS-Phoenix/) -* [Pittsburgh, PA - ReactJS/React Native](https://www.meetup.com/ReactPgh/) -* [Portland, OR - ReactJS](https://www.meetup.com/Portland-ReactJS/) * [Provo, UT - ReactJS](https://www.meetup.com/ReactJS-Utah/) -* [Sacramento, CA - ReactJS](https://www.meetup.com/Sacramento-ReactJS-Meetup/) * [San Diego, CA - San Diego JS](https://www.meetup.com/sandiegojs/) * [San Francisco - Real World React](https://www.meetup.com/Real-World-React) * [San Francisco - ReactJS](https://www.meetup.com/ReactJS-San-Francisco/) * [San Francisco, CA - React Native](https://www.meetup.com/React-Native-San-Francisco/) -* [San Ramon, CA - TriValley Coders](https://www.meetup.com/trivalleycoders/) * [Santa Monica, CA - ReactJS](https://www.meetup.com/Los-Angeles-ReactJS-User-Group/) -* [Seattle, WA - React Native](https://www.meetup.com/Seattle-React-Native-Meetup/) * [Seattle, WA - ReactJS](https://www.meetup.com/seattle-react-js/) * [Tampa, FL - ReactJS](https://www.meetup.com/ReactJS-Tampa-Bay/) * [Tucson, AZ - ReactJS](https://www.meetup.com/Tucson-ReactJS-Meetup/) diff --git a/src/content/community/team.md b/src/content/community/team.md index 6004476e2..94f31f09f 100644 --- a/src/content/community/team.md +++ b/src/content/community/team.md @@ -18,7 +18,7 @@ Current members of the React team are listed in alphabetical order below. Andrew got started with web development by making sites with WordPress, and eventually tricked himself into doing JavaScript. His favorite pastime is karaoke. Andrew is either a Disney villain or a Disney princess, depending on the day. - + Dan got into programming after he accidentally discovered Visual Basic inside Microsoft PowerPoint. He has found his true calling in turning [Sebastian](#sebastian-markbåge)'s tweets into long-form blog posts. Dan occasionally wins at Fortnite by hiding in a bush until the game ends. @@ -38,12 +38,12 @@ Current members of the React team are listed in alphabetical order below. Joe was planning to major in math and philosophy but got into computer science after writing physics simulations in Matlab. Prior to React, he worked on Relay, RSocket.js, and the Skip programming language. While he’s not building some sort of reactive system he enjoys running, studying Japanese, and spending time with his family. - + Josh majored in Mathematics and discovered programming while in college. His first professional developer job was to program insurance rate calculations in Microsoft Excel, the paragon of Reactive Programming which must be why he now works on React. In between that time Josh has been an IC, Manager, and Executive at a few startups. outside of work he likes to push his limits with cooking. - - Lauren's programming career peaked when she first discovered the `` tag. She’s been chasing that high ever since. She studied Finance instead of CS in college, so she learned to code using Excel instead of Java. Lauren enjoys dropping cheeky memes in chat, playing video games with her partner, and petting her dog Zelda. + + Lauren's programming career peaked when she first discovered the `` tag. She’s been chasing that high ever since. She studied Finance instead of CS in college, so she learned to code using Excel. Lauren enjoys dropping cheeky memes in chat, playing video games with her partner, learning Korean, and petting her dog Zelda. @@ -62,7 +62,7 @@ Current members of the React team are listed in alphabetical order below. Noah’s interest in UI programming sparked during his education in music technology at NYU. At Meta, he's worked on internal tools, browsers, web performance, and is currently focused on React. Outside of work, Noah can be found tinkering with synthesizers or spending time with his cat. - + Ricky majored in theoretical math and somehow found himself on the React Native team for a couple years before joining the React team. When he's not programming you can find him snowboarding, biking, climbing, golfing, or closing GitHub issues that do not match the issue template. diff --git a/src/content/learn/add-react-to-an-existing-project.md b/src/content/learn/add-react-to-an-existing-project.md index 370f5e362..bb846e16e 100644 --- a/src/content/learn/add-react-to-an-existing-project.md +++ b/src/content/learn/add-react-to-an-existing-project.md @@ -34,7 +34,7 @@ title: Інтеграція React в існуючий проект Ви можете зробити це у два кроки: -1. **Налаштуйте JavaScript середовище**, яке б дозволяло вам використовувати [JSX синтаксис](/learn/writing-markup-with-jsx), розділіть ваш код на модулі з [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) / [`export`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) синтаксисом і користуйтеся пакетами (наприклад, React) з [npm](https://www.npmjs.com/) реєстру пакетів. +1. **Налаштуйте JavaScript середовище**, яке б дозволяло вам використовувати [JSX синтаксис](/learn/writing-markup-with-jsx), розділіть ваш код на модулі з [`import`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Statements/import) / [`export`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) синтаксисом і користуйтеся пакетами (наприклад, React) з [npm](https://www.npmjs.com/) реєстру пакетів. 2. **Рендеріть ваші React компоненти** там, де ви б хотіли бачити їх на сторінці. Конкретний підхід залежить від налаштувань вашої існуючої сторінки, тому розглянемо деякі деталі. diff --git a/src/content/learn/conditional-rendering.md b/src/content/learn/conditional-rendering.md index d569c39e8..d0c018e64 100644 --- a/src/content/learn/conditional-rendering.md +++ b/src/content/learn/conditional-rendering.md @@ -52,13 +52,13 @@ export default function PackingList() { -Зверніть увагу, що деякі компоненти `Item` мають проп `isPacked` встановлений на `true` замість `false`. Ви хочете додати позначку (✔) до запакованих речей, якщо `isPacked={true}`. +Зверніть увагу, що деякі компоненти `Item` мають проп `isPacked` встановлений на `true` замість `false`. Ви хочете додати позначку (✅) до запакованих речей, якщо `isPacked={true}`. -Ви можете зробити це за допомогою [оператора `if`/`else`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) ось так: +Ви можете зробити це за допомогою [оператора `if`/`else`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Statements/if...else) ось так: ```js if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; ``` @@ -70,7 +70,7 @@ return
  • {name}
  • ; ```js function Item({ name, isPacked }) { if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; } @@ -159,7 +159,7 @@ export default function PackingList() { У попередньому прикладі ви контролювали, яке JSX-дерево буде повернено компонентом. Ви вже могли помітити деяке дублювання у виводі рендеру: ```js -
  • {name} ✔
  • +
  • {name} ✅
  • ``` дуже схоже на @@ -172,7 +172,7 @@ export default function PackingList() { ```js if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; ``` @@ -181,13 +181,13 @@ return
  • {name}
  • ; ### Умовний (тернарний) оператор (`? :`) {/*conditional-ternary-operator--*/} -JavaScript має компактний синтаксис для написання умовного виразу -- [умовний оператор](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) або "тернарний оператор". +JavaScript має компактний синтаксис для написання умовного виразу -- [умовний оператор](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Operators/Conditional_operator) або "тернарний оператор". Замість цього: ```js if (isPacked) { - return
  • {name} ✔
  • ; + return
  • {name} ✅
  • ; } return
  • {name}
  • ; ``` @@ -197,12 +197,12 @@ return
  • {name}
  • ; ```js return (
  • - {isPacked ? name + ' ✔' : name} + {isPacked ? name + ' ✅' : name}
  • ); ``` -Це можна прочитати як *"якщо `isPacked` є true, тоді (`?`) відобразити `name + ' ✔'`, в іншому випадку (`:`) відобразити `name`"*. +Це можна прочитати як *"якщо `isPacked` є true, тоді (`?`) рендерити `name + ' ✅'`, в іншому випадку (`:`) рендерити `name`"*. @@ -222,7 +222,7 @@ function Item({ name, isPacked }) {
  • {isPacked ? ( - {name + ' ✔'} + {name + ' ✅'} ) : ( name @@ -260,12 +260,12 @@ export default function PackingList() { ### Логічний оператор AND (`&&`) {/*logical-and-operator-*/} -Ще одне поширене скорочення, з яким ви зіткнетеся -- [логічний оператор AND (`&&`) JavaScript.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%26%20)%20operator,it%20returns%20a%20Boolean%20value.) Всередині компонентів React він часто з'являється, коли ви хочете відрендерити деякий JSX, коли умова є `true`, **або нічого не рендерити в іншому випадку.** З `&&` ви могли б умовно відрендерити позначку, лише якщо `isPacked` є `true`: +Ще одне поширене скорочення, з яким ви зіткнетеся -- [логічний оператор AND (`&&`) JavaScript.](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%26%20)%20operator,it%20returns%20a%20Boolean%20value.) Всередині компонентів React він часто з'являється, коли ви хочете відрендерити деякий JSX, коли умова є `true`, **або нічого не рендерити в іншому випадку.** З `&&` ви могли б умовно відрендерити позначку, лише якщо `isPacked` є `true`: ```js return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); ``` @@ -280,7 +280,7 @@ return ( function Item({ name, isPacked }) { return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); } @@ -310,7 +310,7 @@ export default function PackingList() { -[JavaScript && вираз](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) повертає значення своєї правої сторони (у нашому випадку, позначку) якщо ліва сторона (наша умова) `true`. Але якщо умова `false`, то весь вираз стає `false`. React розглядає `false` як "діру" в JSX дереві, так само як `null` або `undefined`, і не рендерить нічого на його місці. +[JavaScript && вираз](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Operators/Logical_AND) повертає значення своєї правої сторони (у нашому випадку, позначку) якщо ліва сторона (наша умова) `true`. Але якщо умова `false`, то весь вираз стає `false`. React розглядає `false` як "діру" в JSX дереві, так само як `null` або `undefined`, і не рендерить нічого на його місці. @@ -327,7 +327,7 @@ export default function PackingList() { ### Умовне присвоєння JSX змінній {/*conditionally-assigning-jsx-to-a-variable*/} -Коли скорочення заважають писати звичайний код, спробуйте використати оператор `if` та змінну. Ви можете переприсвоювати змінні, визначені за допомогою [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), тому почніть з задання вмісту за замовчуванням, який ви хочете відобразити, name: +Коли скорочення заважають писати звичайний код, спробуйте використати оператор `if` та змінну. Ви можете переприсвоювати змінні, визначені за допомогою [`let`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Statements/let), тому почніть з задання вмісту за замовчуванням, який ви хочете відобразити, name: ```js let itemContent = name; @@ -337,7 +337,7 @@ let itemContent = name; ```js if (isPacked) { - itemContent = name + " ✔"; + itemContent = name + " ✅"; } ``` @@ -357,7 +357,7 @@ if (isPacked) { function Item({ name, isPacked }) { let itemContent = name; if (isPacked) { - itemContent = name + " ✔"; + itemContent = name + " ✅"; } return (
  • @@ -401,7 +401,7 @@ function Item({ name, isPacked }) { if (isPacked) { itemContent = ( - {name + " ✔"} + {name + " ✅"} ); } @@ -464,7 +464,7 @@ export default function PackingList() { function Item({ name, isPacked }) { return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); } @@ -502,7 +502,7 @@ export default function PackingList() { function Item({ name, isPacked }) { return (
  • - {name} {isPacked ? '✔' : '❌'} + {name} {isPacked ? '✅' : '❌'}
  • ); } diff --git a/src/content/learn/describing-the-ui.md b/src/content/learn/describing-the-ui.md index baf55ba56..a7a156d15 100644 --- a/src/content/learn/describing-the-ui.md +++ b/src/content/learn/describing-the-ui.md @@ -327,7 +327,7 @@ export function getImageUrl(person, size = 's') { function Item({ name, isPacked }) { return (
  • - {name} {isPacked && '✔'} + {name} {isPacked && '✅'}
  • ); } diff --git a/src/content/learn/index.md b/src/content/learn/index.md index 25d7e1af1..89d645937 100644 --- a/src/content/learn/index.md +++ b/src/content/learn/index.md @@ -95,7 +95,7 @@ function AboutPage() { ## Додавання стилів {/*adding-styles*/} -У React, ви вказуєте клас CSS за допомогою `className`. Він працює так само, як атрибут [`class`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class) у HTML: +У React, ви вказуєте клас CSS за допомогою `className`. Він працює так само, як атрибут [`class`](https://webdoky.org/uk/docs/Web/HTML/Global_attributes/class) у HTML: ```js @@ -111,7 +111,7 @@ function AboutPage() { ``` -React не вказує, як додавати файли CSS. У найпростішому випадку ви додасте тег [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) до свого HTML. Якщо ви використовуєте інструмент збірки або фреймворк, зверніться до його документації, щоб дізнатися, як додати файл CSS до вашого проекту. +React не вказує, як додавати файли CSS. У найпростішому випадку ви додасте тег [``](https://webdoky.org/uk/docs/Web/HTML/Element/link) до свого HTML. Якщо ви використовуєте інструмент збірки або фреймворк, зверніться до його документації, щоб дізнатися, як додати файл CSS до вашого проекту. ## Відображення даних {/*displaying-data*/} @@ -182,7 +182,7 @@ export default function Profile() { ## Умовний рендер {/*conditional-rendering*/} -У React немає спеціального синтаксису для запису умов. Замість цього ви будете використовувати ті ж прийоми, що й під час написання звичайного JavaScript коду. Наприклад, ви можете використовувати оператор [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else), щоб умовно включати JSX: +У React немає спеціального синтаксису для запису умов. Замість цього ви будете використовувати ті ж прийоми, що й під час написання звичайного JavaScript коду. Наприклад, ви можете використовувати оператор [`if`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Statements/if...else), щоб умовно включати JSX: ```js let content; @@ -198,7 +198,7 @@ return ( ); ``` -Якщо ви віддаєте перевагу більш компактному коду, ви можете використовувати [умовний оператор `?`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). На відміну від `if`, він працює в JSX: +Якщо ви віддаєте перевагу більш компактному коду, ви можете використовувати [умовний оператор `?`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Operators/Conditional_operator). На відміну від `if`, він працює в JSX: ```js
    @@ -210,7 +210,7 @@ return (
    ``` -Якщо вам не потрібна гілка `else`, ви також можете використовувати коротший [логічний синтаксис `&&`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#short-circuit_evaluation): +Якщо вам не потрібна гілка `else`, ви також можете використовувати коротший [логічний синтаксис `&&`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Operators/Logical_AND#zakorochennia-obchyslennia): ```js
    @@ -221,7 +221,7 @@ return ( ## Рендер списків {/*rendering-lists*/} -Для рендеру списків компонентів ви будете покладатися на такі особливості JavaScript, як [цикл `for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) та [метод масивів `map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). +Для рендеру списків компонентів ви будете покладатися на такі особливості JavaScript, як [цикл `for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) та [метод масивів `map()`](https://webdoky.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Наприклад, припустімо, що у вас є масив продуктів: diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 2d44d7353..e366ea7cc 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -124,35 +124,35 @@ export default function CatFriends() { <>
    • Tom
    • Maru
    • Jellylorum
    • @@ -245,9 +245,9 @@ export default function CatFriends() { return ( <>
        @@ -256,11 +256,11 @@ export default function CatFriends() { key={cat} ref={(node) => { const map = getMap(); - if (node) { - map.set(cat, node); - } else { + map.set(cat, node); + + return () => { map.delete(cat); - } + }; }} > @@ -309,42 +309,10 @@ li { } ``` -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0" - } -} -``` - In this example, `itemsRef` doesn't hold a single DOM node. Instead, it holds a [Map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) from item ID to a DOM node. ([Refs can hold any values!](/learn/referencing-values-with-refs)) The [`ref` callback](/reference/react-dom/components/common#ref-callback) on every list item takes care to update the Map: -```js -
      • { - const map = getMap(); - if (node) { - // Add to the Map - map.set(cat, node); - } else { - // Remove from the Map - map.delete(cat); - } - }} -> -``` - -This lets you read individual DOM nodes from the Map later. - - - -This example shows another approach for managing the Map with a `ref` callback cleanup function. - ```js
      • ``` - +This lets you read individual DOM nodes from the Map later. + + + +When Strict Mode is enabled, ref callbacks will run twice in development. + +Read more about [how this helps find bugs](/reference/react/StrictMode#fixing-bugs-found-by-re-running-ref-callbacks-in-development) in callback refs. + + ## Accessing another component's DOM nodes {/*accessing-another-components-dom-nodes*/} -When you put a ref on a built-in component that outputs a browser element like ``, React will set that ref's `current` property to the corresponding DOM node (such as the actual `` in the browser). + +Refs are an escape hatch. Manually manipulating _another_ component's DOM nodes can make your code fragile. + -However, if you try to put a ref on **your own** component, like ``, by default you will get `null`. Here is an example demonstrating it. Notice how clicking the button **does not** focus the input: - - +You can pass refs from parent component to child components [just like any other prop](/learn/passing-props-to-a-component). -```js +```js {3-4,9} import { useRef } from 'react'; -function MyInput(props) { - return ; +function MyInput({ ref }) { + return ; } -export default function MyForm() { +function MyForm() { const inputRef = useRef(null); - - function handleClick() { - inputRef.current.focus(); - } - - return ( - <> - - - - ); + return } ``` - - -To help you notice the issue, React also prints an error to the console: - - - -Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? - - - -This happens because by default React does not let a component access the DOM nodes of other components. Not even for its own children! This is intentional. Refs are an escape hatch that should be used sparingly. Manually manipulating _another_ component's DOM nodes makes your code even more fragile. - -Instead, components that _want_ to expose their DOM nodes have to **opt in** to that behavior. A component can specify that it "forwards" its ref to one of its children. Here's how `MyInput` can use the `forwardRef` API: - -```js -const MyInput = forwardRef((props, ref) => { - return ; -}); -``` - -This is how it works: - -1. `` tells React to put the corresponding DOM node into `inputRef.current`. However, it's up to the `MyInput` component to opt into that--by default, it doesn't. -2. The `MyInput` component is declared using `forwardRef`. **This opts it into receiving the `inputRef` from above as the second `ref` argument** which is declared after `props`. -3. `MyInput` itself passes the `ref` it received to the `` inside of it. +In the above example, a ref is created in the parent component, `MyForm`, and is passed to the child component, `MyInput`. `MyInput` then passes the ref to ``. Because `` is a [built-in component](/reference/react-dom/components/common) React sets the `.current` property of the ref to the `` DOM element. -Now clicking the button to focus the input works: +The `inputRef` created in `MyForm` now points to the `` DOM element returned by `MyInput`. A click handler created in `MyForm` can access `inputRef` and call `focus()` to set the focus on ``. ```js -import { forwardRef, useRef } from 'react'; +import { useRef } from 'react'; -const MyInput = forwardRef((props, ref) => { - return ; -}); +function MyInput({ ref }) { + return ; +} -export default function Form() { +export default function MyForm() { const inputRef = useRef(null); function handleClick() { @@ -455,24 +395,18 @@ export default function Form() { -In design systems, it is a common pattern for low-level components like buttons, inputs, and so on, to forward their refs to their DOM nodes. On the other hand, high-level components like forms, lists, or page sections usually won't expose their DOM nodes to avoid accidental dependencies on the DOM structure. - #### Exposing a subset of the API with an imperative handle {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} -In the above example, `MyInput` exposes the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with `useImperativeHandle`: +In the above example, the ref passed to `MyInput` is passed on to the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with [`useImperativeHandle`](/reference/react/useImperativeHandle): ```js -import { - forwardRef, - useRef, - useImperativeHandle -} from 'react'; +import { useRef, useImperativeHandle } from "react"; -const MyInput = forwardRef((props, ref) => { +function MyInput({ ref }) { const realInputRef = useRef(null); useImperativeHandle(ref, () => ({ // Only expose focus and nothing else @@ -480,8 +414,8 @@ const MyInput = forwardRef((props, ref) => { realInputRef.current.focus(); }, })); - return ; -}); + return ; +}; export default function Form() { const inputRef = useRef(null); @@ -493,9 +427,7 @@ export default function Form() { return ( <> - + ); } @@ -503,7 +435,7 @@ export default function Form() { -Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, `useImperativeHandle` instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside `useImperativeHandle` call. +Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, [`useImperativeHandle`](/reference/react/useImperativeHandle) instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside [`useImperativeHandle`](/reference/react/useImperativeHandle) call. @@ -615,7 +547,7 @@ export default function TodoList() { const newTodo = { id: nextId++, text: text }; flushSync(() => { setText(''); - setTodos([ ...todos, newTodo]); + setTodos([ ...todos, newTodo]); }); listRef.current.lastChild.scrollIntoView({ behavior: 'smooth', @@ -948,7 +880,7 @@ const catList = []; for (let i = 0; i < 10; i++) { catList.push({ id: i, - imageUrl: 'https://placekitten.com/250/200?image=' + i + imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i }); } @@ -1065,7 +997,7 @@ const catList = []; for (let i = 0; i < 10; i++) { catList.push({ id: i, - imageUrl: 'https://placekitten.com/250/200?image=' + i + imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i }); } 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 41de6529a..1ec4549dc 100644 --- a/src/content/learn/queueing-a-series-of-state-updates.md +++ b/src/content/learn/queueing-a-series-of-state-updates.md @@ -1,23 +1,23 @@ --- -title: Queueing a Series of State Updates +title: Додавання до черги низки оновлень стану --- -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. +Задання значення змінній стану ставить у чергу ще один рендер. Проте іноді може виникнути потреба виконати кілька операцій над значенням, перш ніж додавати до черги новий рендер. Щоб це зробити, корисно розуміти, як React групує оновлення стану. -* 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 використовує його для обробки кількох оновлень стану +* Як застосувати кілька оновлень до однієї змінної стану підряд -## React batches state updates {/*react-batches-state-updates*/} +## React групує оновлення стану {/*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: +Можна було б очікувати, що клацання кнопки "+3" збільшить лічильник тричі, тому що воно викликає тричі `setNumber(number + 1)`: @@ -47,7 +47,7 @@ h1 { display: inline-block; margin: 10px; width: 30px; text-align: center; } -However, as you might recall from the previous section, [each render's state values are fixed](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time), so the value of `number` inside the first render's event handler is always `0`, no matter how many times you call `setNumber(1)`: +Проте, як ви можете пригадати з минулого розділу, [значення стану в кожному рендері — зафіксовані](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time), тож значення `number` всередині обробника подій першого рендеру — завжди `0`, незалежно від того, скільки разів викликати `setNumber(1)`: ```js setNumber(0 + 1); @@ -55,21 +55,21 @@ 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. +Але тут грає роль ще один чинник. **React чекає, поки не виконається *весь* код у обробниках подій, перш ніж обробляти ваші оновлення стану.** Саме тому повторний рендер відбувається *після* всіх цих викликів `setNumber()`. -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. +Це дає змогу оновлювати кілька змінних стану — навіть із різних компонентів — не запускаючи забагато [повторних рендерів.](/learn/render-and-commit#re-renders-when-state-updates) Але це також означає, що UI не оновиться _до_ завершення вашого обробника події та всього коду з нього. Така логіка, також відома як **групування,** значно пришвидшує ваш застосунок на React. Також це позбавляє потреби мати справу з безглуздими "напівготовими" рендерами, в яких оновилась лише частина змінних. -**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. +**React не групує докупи оновлення з *різних* свідомих дій штибу клацань**: кожне клацання обробляється окремо. Будьте певні: React групує лише тоді, коли це загалом безпечно. Завдяки цьому, наприклад, можна мати певність, що якщо перше клацання кнопкою вимикає форму, то друге клацання не пошле цю ж форму знову. -## 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. +Це непоширений випадок використання, але якщо вам хочеться оновити ту саму змінну стану кілька разів до наступного рендеру, то замість передавання *значення наступного стану* виду `setNumber(number + 1)` можна передати *функцію*, яка обчислює наступний стан на основі попереднього стану в черзі, виду `setNumber(n => n + 1)`. Це спосіб сказати React "зробити щось зі значенням стану" замість простої його заміни. -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: +Тут `n => n + 1` зветься **функцією-оновлювачем.** Коли ви передаєте її функції задання стану: -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. +1. React додає цю функцію в чергу до обробки, коли решта коду в обробнику події завершилася. +2. Під час наступного рендеру React йде чергою та видає остаточний оновлений стан. ```js setNumber(n => n + 1); @@ -110,26 +110,26 @@ setNumber(n => n + 1); setNumber(n => n + 1); ``` -Here's how React works through these lines of code while executing the event handler: +Ось як React проходить цими рядками коду, виконуючи обробник подій: -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. -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` — це функція. React додає її до черги. +1. `setNumber(n => n + 1)`: `n => n + 1` — це функція. React додає її до черги. +1. `setNumber(n => n + 1)`: `n => n + 1` — це функція. React додає її до черги. -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: +Коли `useState` викликається під час наступного рендеру, React проходить чергою. Попередній стан `number` був `0`, і це саме те, що React передає до першої функції-оновлювача як аргумент `n`. Потім React бере повернене значення нашої попередньої функції-оновлювача й передає його до наступного оновлювача як `n`, і так далі: -| queued update | `n` | returns | -|--------------|---------|-----| -| `n => n + 1` | `0` | `0 + 1 = 1` | -| `n => n + 1` | `1` | `1 + 1 = 2` | -| `n => n + 1` | `2` | `2 + 1 = 3` | +| оновлення в черзі | `n` | повертає | +| ----------------- | --- | ----------- | +| `n => n + 1` | `0` | `0 + 1 = 1` | +| `n => n + 1` | `1` | `1 + 1 = 2` | +| `n => n + 1` | `2` | `2 + 1 = 3` | -React stores `3` as the final result and returns it from `useState`. +React зберігає `3` як остаточний результат і повертає його з `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*/} +Саме тому клацання "+3" у прикладі вище коректно збільшує значення на 3. +### Що відбудеться, якщо оновити стан, спершу замінивши його {/*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? +Як щодо цього обробника подій? Як гадаєте, яке значення матиме `number` у наступному рендері? ```js + }}>Збільшити число ) } @@ -165,29 +165,29 @@ h1 { display: inline-block; margin: 10px; width: 30px; text-align: center; } -Here's what this event handler tells React to do: +Ось що цей обробник подій каже зробити React: -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. +1. `setNumber(number + 5)`: `number` дорівнює `0`, тож `setNumber(0 + 5)`. React додає до своєї черги *"замінити на `5`"*. +2. `setNumber(n => n + 1)`: `n => n + 1` — це функція-оновлювач. React додає до своєї черги *цю функцію*. -During the next render, React goes through the state queue: +Під час наступного рендеру React проходить по черзі стану: -| queued update | `n` | returns | -|--------------|---------|-----| -| "replace with `5`" | `0` (unused) | `5` | -| `n => n + 1` | `5` | `5 + 1 = 6` | +| оновлення в черзі | `n` | замінити | +| ----------------- | ------------------------- | ----------- | +| "замінити на `5`" | `0` (не використовується) | `5` | +| `n => n + 1` | `5` | `5 + 1 = 6` | -React stores `6` as the final result and returns it from `useState`. +React зберігає `6` як остаточний результат і повертає його з `useState`. -You may have noticed that `setState(5)` actually works like `setState(n => 5)`, but `n` is unused! +Ви могли помітити, що `setState(5)` працює фактично як `setState(n => 5)`, але `n` не використовується! -### 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? +Спробуймо ще один приклад. Як гадаєте, що буде в `number` у наступному рендері? ```js + }}>Збільшити число ) } @@ -225,32 +225,32 @@ h1 { display: inline-block; margin: 10px; width: 30px; text-align: center; } -Here's how React works through these lines of code while executing this event handler: +Ось як React обробляє ці рядки коду, виконуючи цей обробник подій: -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. -3. `setNumber(42)`: React adds *"replace with `42`"* to its queue. +1. `setNumber(number + 5)`: `number` дорівнює `0`, тож `setNumber(0 + 5)`. React додає *"замінити на `5`"* до своєї черги. +2. `setNumber(n => n + 1)`: `n => n + 1` — це функція-оновлювач. React додає до своєї черги *цю функцію*. +3. `setNumber(42)`: React додає *"замінити на `42`"* до своєї черги. -During the next render, React goes through the state queue: +Під час наступного рендеру React проходить по черзі стану: -| queued update | `n` | returns | -|--------------|---------|-----| -| "replace with `5`" | `0` (unused) | `5` | -| `n => n + 1` | `5` | `5 + 1 = 6` | -| "replace with `42`" | `6` (unused) | `42` | +| оновлення в черзі | `n` | повертає | +| ------------------ | ------------------------- | ----------- | +| "замінити на `5`" | `0` (не використовується) | `5` | +| `n => n + 1` | `5` | `5 + 1 = 6` | +| "замінити на `42`" | `6` (не використовується) | `42` | -Then React stores `42` as the final result and returns it from `useState`. +React зберігає `42` як остаточний результат і повертає його з `useState`. -To summarize, here's how you can think of what you're passing to the `setNumber` state setter: +Підсумовуючи, ось як можна осмислити те, що передається до функції задання стану `setNumber`: -* **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. +* **Функція-оновлювач** (наприклад, `n => n + 1`) додається до черги. +* **Будь-які інші значення** (наприклад, число `5`) додають до черги "замінити на `5`", ігноруючи все, що вже в черзі. -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. +Коли обробник подій завершується, React запускає повторний рендер. Під час нього React обробляє чергу. Функції-оновлювачі запускаються під час рендерингу, тож **функції-оновлювачі повинні бути [чистими](/learn/keeping-components-pure)** й лише *повертати* результат. Не намагайтеся задавати стан зсередини них чи запускати ще якісь побічні ефекти. У суворому режимі (strict mode) React намагається запустити кожну функцію-оновлювач двічі (відкидаючи другий результат), щоб допомогти з пошуком помилок. -### Naming conventions {/*naming-conventions*/} +### Домовленості про найменування {/*naming-conventions*/} -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)`. +Якщо вам подобається розлогіший код, то іншим прийнятим підходом є повторити повну назву змінної стану, як `setEnabled(enabled => !enabled)`, або скористатися префіксом, як `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. +* Задання стану не змінить її змінну в наявному рендері, проте зробить запит щодо нового рендеру. +* React обробляє оновлення стану тоді, коли обробники подій уже закінчили виконання. Це зветься групуванням. +* Щоб оновити якийсь стан кілька разів у одній події, можна скористатися функцією-оновлювачем `setNumber(n => n + 1)`. @@ -272,13 +272,13 @@ If you prefer more verbose code, another common convention is to repeat the full -#### Fix a request counter {/*fix-a-request-counter*/} +#### Виправлення лічильника запитів {/*fix-a-request-counter*/} -You're working on an art marketplace app that lets the user submit multiple orders for an art item at the same time. Each time the user presses the "Buy" button, the "Pending" counter should increase by one. After three seconds, the "Pending" counter should decrease, and the "Completed" counter should increase. +Ви працюєте над застосунком мистецького торгівельного майданчика, що дає користувачам змогу розміщати кілька замовлень щодо одного предмету мистецтва водночас. Щоразу, коли користувач натискає кнопку "Придбати", лічильник "Очікування" повинен збільшитись на одиницю. За три секунди лічильник "Очікування" повинен зменшитись, а лічильник "Завершено" — збільшитись. -However, the "Pending" counter does not behave as intended. When you press "Buy", it decreases to `-1` (which should not be possible!). And if you click fast twice, both counters seem to behave unpredictably. +Проте лічильник "Очікування" не поводиться як задумано. Коли натиснути "Придбати", він зменшується до `-1` (що не повинно бути можливим!). А якщо двічі швидко клацнути, то обидва лічильники, здається, поводяться непередбачувано. -Why does this happen? Fix both counters. +Чому так відбувається? Виправіть обидва лічильники. @@ -299,13 +299,13 @@ export default function RequestTracker() { return ( <>

        - Pending: {pending} + Очікування: {pending}

        - Completed: {completed} + Завершено: {completed}

        ); @@ -322,7 +322,7 @@ function delay(ms) { -Inside the `handleClick` event handler, the values of `pending` and `completed` correspond to what they were at the time of the click event. For the first render, `pending` was `0`, so `setPending(pending - 1)` becomes `setPending(-1)`, which is wrong. Since you want to *increment* or *decrement* the counters, rather than set them to a concrete value determined during the click, you can instead pass the updater functions: +Усередині обробника подій `handleClick` значення `pending` і `completed` відповідають тому, чим вони були в мить події клацання. Для першого рендеру `pending` було `0`, тож `setPending(pending - 1)` стало `setPending(-1)`, що неправильно. Оскільки ми хочемо *інкрементувати* чи *декрементувати* лічильники, а не задавати їм конкретні значення, визначені під час клацання, можна натомість передати їм функції-оновлювачі: @@ -343,13 +343,13 @@ export default function RequestTracker() { return ( <>

        - Pending: {pending} + Очікування: {pending}

        - Completed: {completed} + Завершено: {completed}

        ); @@ -364,23 +364,23 @@ 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. +Так можна пересвідчитись, що коли інкрементується чи декрементується лічильник, це відбувається відповідно до його *останнього* стану, а не того, яким стан був під час клацання.
        -#### 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. +У цьому завданні ви самі відтворите крихітну частину React з нуля! Це не так важко, як здається. -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. +Погортайте попередньо "пісочницю". Зверніть увагу на те, що у ній показані **чотири тестові випадки.** Вони відповідають прикладам, які ви бачили на цій сторінці вище. Ваше завдання — реалізувати функцію `getFinalState` так, щоб вона повертала коректний результат для кожного з цих випадків. Якщо реалізувати її коректно, то всі чотири тести пройдуть. -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. +Ви отримаєте два аргументи: `baseState` — це початковий стан (наприклад, `0`), а `queue` — це масив, що вміщає мішанину з чисел (наприклад, `5`) і функцій-оновлювачів (наприклад, `n => n + 1`) у тому порядку, в якому вони додані. -Your task is to return the final state, just like the tables on this page show! +Ваше завдання — повернути остаточний стан, як це показано в таблицях на цій сторінці! -If you're feeling stuck, start with this code structure: +Якщо відчуваєте, що застрягли, почніть з цієї структури коду: ```js export function getFinalState(baseState, queue) { @@ -388,9 +388,9 @@ export function getFinalState(baseState, queue) { for (let update of queue) { if (typeof update === 'function') { - // TODO: apply the updater function + // TODO: застосувати функцію-оновлювач } else { - // TODO: replace the state + // TODO: замінити стан } } @@ -398,7 +398,7 @@ export function getFinalState(baseState, queue) { } ``` -Fill out the missing lines! +Заповніть відсутні рядки! @@ -408,7 +408,7 @@ Fill out the missing lines! export function getFinalState(baseState, queue) { let finalState = baseState; - // TODO: do something with the queue... + // TODO: зробити щось із чергою... return finalState; } @@ -471,19 +471,19 @@ function TestCase({ const actual = getFinalState(baseState, queue); return ( <> -

        Base state: {baseState}

        -

        Queue: [{queue.join(', ')}]

        -

        Expected result: {expected}

        +

        Базовий стан: {baseState}

        +

        Черга: [{queue.join(', ')}]

        +

        Очікуваний результат: {expected}

        - Your result: {actual} + Ваш результат: {actual} {' '} ({actual === expected ? - 'correct' : - 'wrong' + 'успіх' : + 'помилка' })

        @@ -495,7 +495,7 @@ function TestCase({ -This is the exact algorithm described on this page that React uses to calculate the final state: +Ось точний алгоритм, описаний на цій сторінці, який React використовує для обчислення остаточного стану: @@ -505,10 +505,10 @@ export function getFinalState(baseState, queue) { for (let update of queue) { if (typeof update === 'function') { - // Apply the updater function. + // Застосувати функцію-оновлювача. finalState = update(finalState); } else { - // Replace the next state. + // Замінити наступний стан. finalState = update; } } @@ -574,19 +574,19 @@ function TestCase({ const actual = getFinalState(baseState, queue); return ( <> -

        Base state: {baseState}

        -

        Queue: [{queue.join(', ')}]

        -

        Expected result: {expected}

        +

        Базовий стан: {baseState}

        +

        Черга: [{queue.join(', ')}]

        +

        Очікуваний результат: {expected}

        - Your result: {actual} + Ваш результат: {actual} {' '} ({actual === expected ? - 'correct' : - 'wrong' + 'успіх' : + 'помилка' })

        @@ -596,7 +596,7 @@ function TestCase({
        -Now you know how this part of React works! +Тепер ви знаєте, як працює ця частина React!
        diff --git a/src/content/learn/react-compiler.md b/src/content/learn/react-compiler.md index f34c382ed..0ae499472 100644 --- a/src/content/learn/react-compiler.md +++ b/src/content/learn/react-compiler.md @@ -3,7 +3,7 @@ title: React Compiler --- -This page will give you an introduction to the new experimental React Compiler and how to try it out successfully. +This page will give you an introduction to React Compiler and how to try it out successfully. @@ -13,20 +13,34 @@ These docs are still a work in progress. More documentation is available in the * Getting started with the compiler -* Installing the compiler and eslint plugin +* Installing the compiler and ESLint plugin * Troubleshooting -React Compiler is a new experimental compiler that we've open sourced to get early feedback from the community. It still has rough edges and is not yet fully ready for production. +React Compiler is a new compiler currently in Beta, that we've open sourced to get early feedback from the community. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you’ve followed the [Rules of React](/reference/rules). -React Compiler requires React 19 RC. If you are unable to upgrade to React 19, you may try a userspace implementation of the cache function as described in the [Working Group](https://github.com/reactwg/react-compiler/discussions/6). However, please note that this is not recommended and you should upgrade to React 19 when possible. +The latest Beta release can be found with the `@beta` tag, and daily experimental releases with `@experimental`. -React Compiler is a new experimental compiler that we've open sourced to get early feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it. +React Compiler is a new compiler that we've open sourced to get early feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it. -The compiler also includes an [eslint plugin](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. The plugin runs independently of the compiler and can be used even if you aren't using the compiler in your app. We recommend all React developers to use this eslint plugin to help improve the quality of your codebase. +The compiler also includes an [ESLint plugin](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. **We strongly recommend everyone use the linter today.** The linter does not require that you have the compiler installed, so you can use it even if you are not ready to try out the compiler. + +The compiler is currently released as `beta`, and is available to try out on React 17+ apps and libraries. To install the Beta: + + +npm install -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta + + +Or, if you're using Yarn: + + +yarn add -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta + + +If you are not using React 19 yet, please see [the section below](#using-react-compiler-with-react-17-or-18) for further instructions. ### What does the compiler do? {/*what-does-the-compiler-do*/} @@ -34,6 +48,10 @@ In order to optimize applications, React Compiler automatically memoizes your co The compiler uses its knowledge of JavaScript and React's rules to automatically memoize values or groups of values within your components and hooks. If it detects breakages of the rules, it will automatically skip over just those components or hooks, and continue safely compiling other code. + +React Compiler can statically detect when Rules of React are broken, and safely opt-out of optimizing just the affected components or hooks. It is not necessary for the compiler to optimize 100% of your codebase. + + If your codebase is already very well-memoized, you might not expect to see major performance improvements with the compiler. However, in practice memoizing the correct dependencies that cause performance issues is tricky to get right by hand. @@ -96,19 +114,9 @@ However, if `expensivelyProcessAReallyLargeArrayOfObjects` is truly an expensive So if `expensivelyProcessAReallyLargeArrayOfObjects` was used in many different components, even if the same exact items were passed down, that expensive calculation would be run repeatedly. We recommend [profiling](https://react.dev/reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive) first to see if it really is that expensive before making code more complicated. -### What does the compiler assume? {/*what-does-the-compiler-assume*/} - -React Compiler assumes that your code: - -1. Is valid, semantic JavaScript -2. Tests that nullable/optional values and properties are defined before accessing them (for example, by enabling [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) if using TypeScript), i.e., `if (object.nullableProperty) { object.nullableProperty.foo }` or with optional-chaining `object.nullableProperty?.foo` -3. Follows the [Rules of React](https://react.dev/reference/rules) - -React Compiler can verify many of the Rules of React statically, and will safely skip compilation when it detects an error. To see the errors we recommend also installing [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler). - ### Should I try out the compiler? {/*should-i-try-out-the-compiler*/} -Please note that the compiler is still experimental and has many rough edges. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules). +Please note that the compiler is still in Beta and has many rough edges. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules). **You don't have to rush into using the compiler now. It's okay to wait until it reaches a stable release before adopting it.** However, we do appreciate trying it out in small experiments in your apps so that you can [provide feedback](#reporting-issues) to us to help make the compiler better. @@ -116,37 +124,32 @@ Please note that the compiler is still experimental and has many rough edges. Wh In addition to these docs, we recommend checking the [React Compiler Working Group](https://github.com/reactwg/react-compiler) for additional information and discussion about the compiler. -### Checking compatibility {/*checking-compatibility*/} - -Prior to installing the compiler, you can first check to see if your codebase is compatible: - - -npx react-compiler-healthcheck@latest - - -This script will: - -- Check how many components can be successfully optimized: higher is better -- Check for `` usage: having this enabled and followed means a higher chance that the [Rules of React](/reference/rules) are followed -- Check for incompatible library usage: known libraries that are incompatible with the compiler +### Installing eslint-plugin-react-compiler {/*installing-eslint-plugin-react-compiler*/} -As an example: +React Compiler also powers an ESLint plugin. The ESLint plugin can be used **independently** of the compiler, meaning you can use the ESLint plugin even if you don't use the compiler. -Successfully compiled 8 out of 9 components. -StrictMode usage not found. -Found no usage of incompatible libraries. +npm install -D eslint-plugin-react-compiler@beta -### Installing eslint-plugin-react-compiler {/*installing-eslint-plugin-react-compiler*/} - -React Compiler also powers an eslint plugin. The eslint plugin can be used **independently** of the compiler, meaning you can use the eslint plugin even if you don't use the compiler. +Then, add it to your ESLint config: - -npm install eslint-plugin-react-compiler - +```js +import reactCompiler from 'eslint-plugin-react-compiler' + +export default [ + { + plugins: { + 'react-compiler': reactCompiler, + }, + rules: { + 'react-compiler/react-compiler': 'error', + }, + }, +] +``` -Then, add it to your eslint config: +Or, in the deprecated eslintrc config format: ```js module.exports = { @@ -154,14 +157,16 @@ module.exports = { 'eslint-plugin-react-compiler', ], rules: { - 'react-compiler/react-compiler': "error", + 'react-compiler/react-compiler': 'error', }, } ``` -The eslint plugin will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase. +The ESLint plugin will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase. -**You don't have to fix all eslint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized, but it is not required to fix everything before you can use the compiler. + +**You don't have to fix all ESLint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized, but it is not required to fix everything before you can use the compiler. + ### Rolling out the compiler to your codebase {/*using-the-compiler-effectively*/} @@ -178,32 +183,53 @@ const ReactCompilerConfig = { }; ``` -In rare cases, you can also configure the compiler to run in "opt-in" mode using the `compilationMode: "annotation"` option. This makes it so the compiler will only compile components and hooks annotated with a `"use memo"` directive. Please note that the `annotation` mode is a temporary one to aid early adopters, and that we don't intend for the `"use memo"` directive to be used for the long term. +When you have more confidence with rolling out the compiler, you can expand coverage to other directories as well and slowly roll it out to your whole app. -```js {2,7} +#### New projects {/*new-projects*/} + +If you're starting a new project, you can enable the compiler on your entire codebase, which is the default behavior. + +### Using React Compiler with React 17 or 18 {/*using-react-compiler-with-react-17-or-18*/} + +React Compiler works best with React 19 RC. If you are unable to upgrade, you can install the extra `react-compiler-runtime` package which will allow the compiled code to run on versions prior to 19. However, note that the minimum supported version is 17. + + +npm install react-compiler-runtime@beta + + +You should also add the correct `target` to your compiler config, where `target` is the major version of React you are targeting: + +```js {3} +// babel.config.js const ReactCompilerConfig = { - compilationMode: "annotation", + target: '18' // '17' | '18' | '19' }; -// src/app.jsx -export default function App() { - "use memo"; - // ... -} +module.exports = function () { + return { + plugins: [ + ['babel-plugin-react-compiler', ReactCompilerConfig], + ], + }; +}; ``` -When you have more confidence with rolling out the compiler, you can expand coverage to other directories as well and slowly roll it out to your whole app. +### Using the compiler on libraries {/*using-the-compiler-on-libraries*/} -#### New projects {/*new-projects*/} +React Compiler can also be used to compile libraries. Because React Compiler needs to run on the original source code prior to any code transformations, it is not possible for an application's build pipeline to compile the libraries they use. Hence, our recommendation is for library maintainers to independently compile and test their libraries with the compiler, and ship compiled code to npm. -If you're starting a new project, you can enable the compiler on your entire codebase, which is the default behavior. +Because your code is pre-compiled, users of your library will not need to have the compiler enabled in order to benefit from the automatic memoization applied to your library. If your library targets apps not yet on React 19, specify a minimum [`target` and add `react-compiler-runtime` as a direct dependency](#using-react-compiler-with-react-17-or-18). The runtime package will use the correct implementation of APIs depending on the application's version, and polyfill the missing APIs if necessary. + +Library code can often require more complex patterns and usage of escape hatches. For this reason, we recommend ensuring that you have sufficient testing in order to identify any issues that might arise from using the compiler on your library. If you identify any issues, you can always opt-out the specific components or hooks with the [`'use no memo'` directive](#something-is-not-working-after-compilation). + +Similarly to apps, it is not necessary to fully compile 100% of your components or hooks to see benefits in your library. A good starting point might be to identify the most performance sensitive parts of your library and ensuring that they don't break the [Rules of React](/reference/rules), which you can use `eslint-plugin-react-compiler` to identify. ## Usage {/*installation*/} ### Babel {/*usage-with-babel*/} -npm install babel-plugin-react-compiler +npm install babel-plugin-react-compiler@beta The compiler includes a Babel plugin which you can use in your build pipeline to run the compiler. @@ -252,36 +278,7 @@ export default defineConfig(() => { ### Next.js {/*usage-with-nextjs*/} -Next.js has an experimental configuration to enable the React Compiler. It automatically ensures Babel is set up with `babel-plugin-react-compiler`. - -- Install Next.js canary, which uses React 19 Release Candidate -- Install `babel-plugin-react-compiler` - - -npm install next@canary babel-plugin-react-compiler - - -Then configure the experimental option in `next.config.js`: - -```js {4,5,6} -// next.config.js -/** @type {import('next').NextConfig} */ -const nextConfig = { - experimental: { - reactCompiler: true, - }, -}; - -module.exports = nextConfig; -``` - -Using the experimental option ensures support for the React Compiler in: - -- App Router -- Pages Router -- Webpack (default) -- Turbopack (opt-in through `--turbo`) - +Please refer to the [Next.js docs](https://nextjs.org/docs/app/api-reference/next-config-js/reactCompiler) for more information. ### Remix {/*usage-with-remix*/} Install `vite-plugin-babel`, and add the compiler's Babel plugin to it: @@ -314,44 +311,11 @@ export default defineConfig({ ### Webpack {/*usage-with-webpack*/} -You can create your own loader for React Compiler, like so: - -```js -const ReactCompilerConfig = { /* ... */ }; -const BabelPluginReactCompiler = require('babel-plugin-react-compiler'); - -function reactCompilerLoader(sourceCode, sourceMap) { - // ... - const result = transformSync(sourceCode, { - // ... - plugins: [ - [BabelPluginReactCompiler, ReactCompilerConfig], - ], - // ... - }); - - if (result === null) { - this.callback( - Error( - `Failed to transform "${options.filename}"` - ) - ); - return; - } - - this.callback( - null, - result.code, - result.map === null ? undefined : result.map - ); -} - -module.exports = reactCompilerLoader; -``` +A community Webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack). ### Expo {/*usage-with-expo*/} -Please refer to [Expo's docs](https://docs.expo.dev/preview/react-compiler/) to enable and use the React Compiler in Expo apps. +Please refer to [Expo's docs](https://docs.expo.dev/guides/react-compiler/) to enable and use the React Compiler in Expo apps. ### Metro (React Native) {/*usage-with-react-native-metro*/} @@ -371,22 +335,26 @@ To report issues, please first create a minimal repro on the [React Compiler Pla You can also provide feedback in the React Compiler Working Group by applying to be a member. Please see [the README for more details on joining](https://github.com/reactwg/react-compiler). -### `(0 , _c) is not a function` error {/*0--_c-is-not-a-function-error*/} +### What does the compiler assume? {/*what-does-the-compiler-assume*/} -This occurs if you are not using React 19 RC and up. To fix this, [upgrade your app to React 19 RC](https://react.dev/blog/2024/04/25/react-19-upgrade-guide) first. +React Compiler assumes that your code: -If you are unable to upgrade to React 19, you may try a userspace implementation of the cache function as described in the [Working Group](https://github.com/reactwg/react-compiler/discussions/6). However, please note that this is not recommended and you should upgrade to React 19 when possible. +1. Is valid, semantic JavaScript. +2. Tests that nullable/optional values and properties are defined before accessing them (for example, by enabling [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) if using TypeScript), i.e., `if (object.nullableProperty) { object.nullableProperty.foo }` or with optional-chaining `object.nullableProperty?.foo`. +3. Follows the [Rules of React](https://react.dev/reference/rules). + +React Compiler can verify many of the Rules of React statically, and will safely skip compilation when it detects an error. To see the errors we recommend also installing [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler). ### How do I know my components have been optimized? {/*how-do-i-know-my-components-have-been-optimized*/} -[React Devtools](/learn/react-developer-tools) (v5.0+) has built-in support for React Compiler and will display a "Memo ✨" badge next to components that have been optimized by the compiler. +[React DevTools](/learn/react-developer-tools) (v5.0+) and [React Native DevTools](https://reactnative.dev/docs/react-native-devtools) have built-in support for React Compiler and will display a "Memo ✨" badge next to components that have been optimized by the compiler. ### Something is not working after compilation {/*something-is-not-working-after-compilation*/} -If you have eslint-plugin-react-compiler installed, the compiler will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase. **You don't have to fix all eslint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized. +If you have eslint-plugin-react-compiler installed, the compiler will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase. **You don't have to fix all ESLint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized. Due to the flexible and dynamic nature of JavaScript however, it's not possible to comprehensively detect all cases. Bugs and undefined behavior such as infinite loops may occur in those cases. -If your app doesn't work properly after compilation and you aren't seeing any eslint errors, the compiler may be incorrectly compiling your code. To confirm this, try to make the issue go away by aggressively opting out any component or hook you think might be related via the [`"use no memo"` directive](#opt-out-of-the-compiler-for-a-component). +If your app doesn't work properly after compilation and you aren't seeing any ESLint errors, the compiler may be incorrectly compiling your code. To confirm this, try to make the issue go away by aggressively opting out any component or hook you think might be related via the [`"use no memo"` directive](#opt-out-of-the-compiler-for-a-component). ```js {2} function SuspiciousComponent() { diff --git a/src/content/learn/react-developer-tools.md b/src/content/learn/react-developer-tools.md index 7ae961362..836187a38 100644 --- a/src/content/learn/react-developer-tools.md +++ b/src/content/learn/react-developer-tools.md @@ -53,24 +53,9 @@ react-devtools ![Автономні 'Інструменти React розробника'](/images/docs/react-devtools-standalone.png) ## Мобільний застосунок (React Native) {/*mobile-react-native*/} -Інструменти React розробника також можна використовувати для інспектування застосунків, створених за допомогою [React Native](https://reactnative.dev/). -Найпростіший спосіб використання інструментів — встановити їх глобально: -```bash -# Yarn -yarn global add react-devtools - -# Npm -npm install -g react-devtools -``` - -Далі відкрийте інструменти розробника з терміналу: -```bash -react-devtools -``` - -Вони повинні під'єднатися до будь-якого локально працюючого застосунку React Native. - -> Спробуйте перезавантажити застосунок, якщо інструменти розробки не під'єднуються протягом кількох секунд. +Для інспектування застосунків, створених за допомогою [React Native](https://reactnative.dev/), можна використовувати [інструменти розробника React Native](https://reactnative.dev/docs/debugging/react-native-devtools) — вбудований налагоджувач, який глибоко інтегрує інструменти розробника React. Усі функції працюють так само, як у розширенні браузера, включно з підсвічуванням та виділенням нативних елементів. [Дізнатися більше про налагодження React Native.](https://reactnative.dev/docs/debugging) + +> Для версій React Native до 0.76, будь ласка, використовуйте автономну (standalone) збірку інструментів розробника React за інструкцією у пункті ["Safari та інші браузери"](#safari-and-other-browsers) вище. \ 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 da559dc0f..685139949 100644 --- a/src/content/learn/reacting-to-input-with-state.md +++ b/src/content/learn/reacting-to-input-with-state.md @@ -1,37 +1,37 @@ --- -title: Reacting to Input with State +title: Реагування станом на введення --- -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 надає декларативний спосіб маніпулювання UI. Замість маніпулювання окремими шматочками UI безпосередньо, слід описувати різні стани, в яких може перебувати компонент, і перемикатися між ними внаслідок користувацького введення. Це схоже на те, як UI уявляють дизайнери. -* How declarative UI programming differs from imperative UI programming -* How to enumerate the different visual states your component can be in -* How to trigger the changes between the different visual states from code +* Як декларативне програмування UI відрізняється від імперативного +* Як перелічити різні візуальні стани, в яких може перебувати компонент +* Як з коду запустити зміни між різними візуальними станами -## How declarative UI compares to imperative {/*how-declarative-ui-compares-to-imperative*/} +## Як декларативний UI відрізняється від імперативного {/*how-declarative-ui-compares-to-imperative*/} -When you design UI interactions, you probably think about how the UI *changes* in response to user actions. Consider a form that lets the user submit an answer: +При розробці взаємодій з UI, ймовірно, ви думаєте про те, як UI *змінюється* внаслідок дій користувача. Уявіть форму, що дає користувачу змогу надіслати відповідь: -* When you type something into the form, the "Submit" button **becomes enabled.** -* When you press "Submit", both the form and the button **become disabled,** and a spinner **appears.** -* If the network request succeeds, the form **gets hidden,** and the "Thank you" message **appears.** -* If the network request fails, an error message **appears,** and the form **becomes enabled** again. +* Коли ви друкуєте щось у формі, кнопка "Надіслати" **стає увімкненою.** +* Коли ви натискаєте "Надіслати", то і форма, і кнопка **стають вимкненими,** і **з'являється** дзиґа. +* Якщо мережевий запит успішний, то форма **ховається,** і **з'являється** повідомлення "Дякуємо". +* Якщо мережевий запит невдалий, то **з'являється** повідомлення про помилку, а форма знову **стає ввімкненою.** -In **imperative programming,** the above corresponds directly to how you implement interaction. You have to write the exact instructions to manipulate the UI depending on what just happened. Here's another way to think about this: imagine riding next to someone in a car and telling them turn by turn where to go. +У **імперативному програмуванні** описане вище безпосередньо відповідає тому, як реалізується взаємодія. Доводиться писати прямі інструкції для маніпулювання UI, залежно від того, що відбувається. Ось іще один спосіб подумати про це: уявіть, що їдете з кимось в авто й керуєте поїздкою, називаючи кожний поворот. - + -They don't know where you want to go, they just follow your commands. (And if you get the directions wrong, you end up in the wrong place!) It's called *imperative* because you have to "command" each element, from the spinner to the button, telling the computer *how* to update the UI. +Водій не знає, куди ви хочете потрапити, він просто виконує команди. (І якщо ви переплутаєте орієнтири, то опинитеся не там!) Це зветься *імперативним*, тому що доводиться "командувати" кожним елементом, від дзиґи до кнопки, кажучи комп'ютеру, *як* оновлювати UI. -In this example of imperative UI programming, the form is built *without* React. It only uses the browser [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model): +У цьому прикладі імперативного програмування UI форма створена *без* React. Вна використовує лише браузерний [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model): @@ -81,13 +81,13 @@ function disable(el) { } function submitForm(answer) { - // Pretend it's hitting the network. + // Зробімо вигляд, що тут відбувається мережевий запит. return new Promise((resolve, reject) => { setTimeout(() => { - if (answer.toLowerCase() === 'istanbul') { + if (answer.toLowerCase() === 'стамбул') { resolve(); } else { - reject(new Error('Good guess but a wrong answer. Try again!')); + reject(new Error('Гарний варіант, але неправильна відповідь. Спробуйте ще!')); } }, 1500); }); @@ -111,17 +111,17 @@ textarea.oninput = handleTextareaChange; ```html public/index.html
        -

        City quiz

        +

        Вікторина міст

        - What city is located on two continents? + Яке місто розташовано на двох континентах?


        - - + +
        -

        That's right!

        +

        Правильно!