Skip to content

Commit

Permalink
Merge pull request #891 from reactjs/sync-a8790ca8
Browse files Browse the repository at this point in the history
Sync with react.dev @ a8790ca
  • Loading branch information
carburo authored Nov 6, 2023
2 parents 6a6f182 + 479f5a9 commit 3f3593f
Show file tree
Hide file tree
Showing 16 changed files with 688 additions and 178 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 3 additions & 3 deletions src/components/Layout/getRouteMeta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ export interface RouteMeta {
order?: number;
}

type TravesalContext = RouteMeta & {
type TraversalContext = RouteMeta & {
currentIndex: number;
};

export function getRouteMeta(cleanedPath: string, routeTree: RouteItem) {
const breadcrumbs = getBreadcrumbs(cleanedPath, routeTree);
const ctx: TravesalContext = {
const ctx: TraversalContext = {
currentIndex: 0,
};
buildRouteMeta(cleanedPath, routeTree, ctx);
Expand All @@ -79,7 +79,7 @@ export function getRouteMeta(cleanedPath: string, routeTree: RouteItem) {
function buildRouteMeta(
searchPath: string,
currentRoute: RouteItem,
ctx: TravesalContext
ctx: TraversalContext
) {
ctx.currentIndex++;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Making plain JavaScript in React components reactive requires a compiler with a

## Offscreen Rendering {/*offscreen-rendering*/}

Offscreen rendering is an upcoming capability in React for rendering screens in the background without additional performance overhead. You can think of it as a version of the [`content-visiblity` CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility) that works not only for DOM elements but React components, too. During our research, we've discovered a variety of use cases:
Offscreen rendering is an upcoming capability in React for rendering screens in the background without additional performance overhead. You can think of it as a version of the [`content-visibility` CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility) that works not only for DOM elements but React components, too. During our research, we've discovered a variety of use cases:

- A router can prerender screens in the background so that when a user navigates to them, they're instantly available.
- A tab switching component can preserve the state of hidden tabs, so the user can switch between them without losing their progress.
Expand Down
2 changes: 1 addition & 1 deletion src/content/reference/react-dom/components/form.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ export async function deliverMessage(message) {

</Sandpack>

[//]: # 'Uncomment the next line, and delete this line after the `useOptimisitc` reference documentatino page is published'
[//]: # 'Uncomment the next line, and delete this line after the `useOptimistic` reference documentatino page is published'
[//]: # 'To learn more about the `useOptimistic` Hook see the [reference documentation](/reference/react/hooks/useOptimistic).'

### Handling form submission errors {/*handling-form-submission-errors*/}
Expand Down
2 changes: 1 addition & 1 deletion src/content/reference/react/Component.md
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@ class Form extends Component {
return (
<>
<input value={this.state.name} onChange={this.handleNameChange} />
<p>Hola, {this.state.name}.
<p>Hola, {this.state.name}.</p>
</>
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/content/reference/react/cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ async function DemoProfile() {
React only provides cache access to the memoized function in a component. When calling <CodeStep step={1}>`getUser`</CodeStep> outside of a component, it will still evaluate the function but not read or update the cache.
This is because cache access is provided through a [context](/learn/passing-data-deeply-with-context) which is only accessibile from a component.
This is because cache access is provided through a [context](/learn/passing-data-deeply-with-context) which is only accessible from a component.
</Pitfall>
Expand Down
2 changes: 1 addition & 1 deletion src/content/reference/react/directives.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ Las directivas proporcionan instrucciones para [bundlers compatibles con React S

## Directivas de código fuente {/*source-code-directives*/}

* [`'use client'`](/reference/react/use-client) marca los ficheros fuente cuyos componentes se ejecutan en el cliente.
* [`'use client'`](/reference/react/use-client) te permite marcar qué código se ejecuta en el cliente.
* [`'use server'`](/reference/react/use-server) marca funciones del lado del servidor que pueden ser llamadas desde código del lado del cliente.
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ In this example, the constant `password` is tainted. Then `password` is used to

Other similar ways of deriving new values from tainted values like concatenating it into a larger string, converting it to base64, or returning a substring create untained values.

Tainting only protects against simple mistakes like explictly passing secret values to the client. Mistakes in calling the `taintUniqueValue` like using a global store outside of React, without the corresponding lifetime object, can cause the tainted value to become untainted. Tainting is a layer of protection; a secure app will have multiple layers of protection, well designed APIs, and isolation patterns.
Tainting only protects against simple mistakes like explicitly passing secret values to the client. Mistakes in calling the `taintUniqueValue` like using a global store outside of React, without the corresponding lifetime object, can cause the tainted value to become untainted. Tainting is a layer of protection; a secure app will have multiple layers of protection, well designed APIs, and isolation patterns.

</Pitfall>

Expand Down
139 changes: 139 additions & 0 deletions src/content/reference/react/hooks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
---
title: "Built-in React Hooks"
---

<Intro>

*Hooks* let you use different React features from your components. You can either use the built-in Hooks or combine them to build your own. This page lists all built-in Hooks in React.

</Intro>

---

## State Hooks {/*state-hooks*/}

*State* lets a component ["remember" information like user input.](/learn/state-a-components-memory) For example, a form component can use state to store the input value, while an image gallery component can use state to store the selected image index.

To add state to a component, use one of these Hooks:

* [`useState`](/reference/react/useState) declares a state variable that you can update directly.
* [`useReducer`](/reference/react/useReducer) declares a state variable with the update logic inside a [reducer function.](/learn/extracting-state-logic-into-a-reducer)

```js
function ImageGallery() {
const [index, setIndex] = useState(0);
// ...
```
---
## Context Hooks {/*context-hooks*/}
*Context* lets a component [receive information from distant parents without passing it as props.](/learn/passing-props-to-a-component) For example, your app's top-level component can pass the current UI theme to all components below, no matter how deep.
* [`useContext`](/reference/react/useContext) reads and subscribes to a context.
```js
function Button() {
const theme = useContext(ThemeContext);
// ...
```
---
## Ref Hooks {/*ref-hooks*/}
*Refs* let a component [hold some information that isn't used for rendering,](/learn/referencing-values-with-refs) like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an "escape hatch" from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.
* [`useRef`](/reference/react/useRef) declares a ref. You can hold any value in it, but most often it's used to hold a DOM node.
* [`useImperativeHandle`](/reference/react/useImperativeHandle) lets you customize the ref exposed by your component. This is rarely used.
```js
function Form() {
const inputRef = useRef(null);
// ...
```
---
## Effect Hooks {/*effect-hooks*/}
*Effects* let a component [connect to and synchronize with external systems.](/learn/synchronizing-with-effects) This includes dealing with network, browser DOM, animations, widgets written using a different UI library, and other non-React code.
* [`useEffect`](/reference/react/useEffect) connects a component to an external system.
```js
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
// ...
```
Effects are an "escape hatch" from the React paradigm. Don't use Effects to orchestrate the data flow of your application. If you're not interacting with an external system, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
There are two rarely used variations of `useEffect` with differences in timing:
* [`useLayoutEffect`](/reference/react/useLayoutEffect) fires before the browser repaints the screen. You can measure layout here.
* [`useInsertionEffect`](/reference/react/useInsertionEffect) fires before React makes changes to the DOM. Libraries can insert dynamic CSS here.
---
## Performance Hooks {/*performance-hooks*/}
A common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell React to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render.
To skip calculations and unnecessary re-rendering, use one of these Hooks:
- [`useMemo`](/reference/react/useMemo) lets you cache the result of an expensive calculation.
- [`useCallback`](/reference/react/useCallback) lets you cache a function definition before passing it down to an optimized component.
```js
function TodoList({ todos, tab, theme }) {
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
// ...
}
```
Sometimes, you can't skip re-rendering because the screen actually needs to update. In that case, you can improve performance by separating blocking updates that must be synchronous (like typing into an input) from non-blocking updates which don't need to block the user interface (like updating a chart).
To prioritize rendering, use one of these Hooks:
- [`useTransition`](/reference/react/useTransition) lets you mark a state transition as non-blocking and allow other updates to interrupt it.
- [`useDeferredValue`](/reference/react/useDeferredValue) lets you defer updating a non-critical part of the UI and let other parts update first.
---
## Resource Hooks {/*resource-hooks*/}
*Resources* can be accessed by a component without having them as part of their state. For example, a component can read a message from a Promise or read styling information from a context.
To read a value from a resource, use this Hook:
- [`use`](/reference/react/use) lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context).
```js
function MessageComponent({ messagePromise }) {
const message = use(messagePromise);
const theme = use(ThemeContext);
// ...
}
```
---
## Other Hooks {/*other-hooks*/}
These Hooks are mostly useful to library authors and aren't commonly used in the application code.
- [`useDebugValue`](/reference/react/useDebugValue) lets you customize the label React DevTools displays for your custom Hook.
- [`useId`](/reference/react/useId) lets a component associate a unique ID with itself. Typically used with accessibility APIs.
- [`useSyncExternalStore`](/reference/react/useSyncExternalStore) lets a component subscribe to an external store.
---
## Your own Hooks {/*your-own-hooks*/}
You can also [define your own custom Hooks](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component) as JavaScript functions.
149 changes: 20 additions & 129 deletions src/content/reference/react/index.md
Original file line number Diff line number Diff line change
@@ -1,139 +1,30 @@
---
title: "Hooks integrados de React"
title: React Reference Overview
---

<Intro>

Los *Hooks* te permiten usar diferentes funciones de React desde tus componentes. Puedes usar los Hooks integrados o combinarlos para construir tu propio Hook. Esta página lista todos los *Hooks integrados* en React.

This section provides detailed reference documentation for working with React.
For an introduction to React, please visit the [Learn](/learn) section.
</Intro>

---

## Hooks de estado {/*state-hooks*/}

El *estado* permite que un componente ["recuerde" información como la entrada de un usuario.](/learn/state-a-components-memory) Por ejemplo, un componente de formulario puede utilizar un estado para guardar la entrada del valor mientras que un componente de galería de imágenes puede utilizar un estado para guardar el índice de la imagen seleccionada.

Para añadir un estado a un componente, usa uno de estos Hooks:

* [`useState`](/reference/react/useState) declara una variable de estado que puedes actualizar directamente.
* [`useReducer`](/reference/react/useReducer) declara una variable de estado con la lógica de actualización dentro de una [función reductora.](/learn/extracting-state-logic-into-a-reducer)

```js
function ImageGallery() {
const [index, setIndex] = useState(0);
// ...
```
---
## Hooks de contexto {/*context-hooks*/}
El *contexto* permite a un componente [recibir información de padres lejanos sin pasarlas como props.](/learn/passing-props-to-a-component) Por ejemplo, el componente en el nivel superior de tu aplicación puede pasar el actual tema de la UI a todos los componentes dentro, sin importar la profundidad dentro del componente.
* [`useContext`](/reference/react/useContext) lee y se subscribe a un contexto.
```js
function Button() {
const theme = useContext(ThemeContext);
// ...
```
---
## Hooks de refs {/*ref-hooks*/}
Las *refs* le permiten a un componente [mantener alguna información que no es utilizada para el renderizado](/learn/referencing-values-with-refs) como un nodo del DOM o el ID de un *timeout*. A diferencia del estado, actualizar una *ref* no vuelve a renderizar tu componente. Las *refs* son una "puerta de escape" del paradigma de React. Son útiles cuando necesitas trabajar con sistemas distintos de React, como las APIs integradas del navegador.
* [`useRef`](/reference/react/useRef) declara una ref. Puede contener cualquier valor, pero la mayoría de las veces se utiliza para contener un nodo del DOM.
* [`useImperativeHandle`](/reference/react/useImperativeHandle) permite personalizar la *ref* expuesta por tu componente. Esto rara vez se usa.
```js
function Form() {
const inputRef = useRef(null);
// ...
```
---
## Hooks de Efecto {/*effect-hooks*/}
El *Hook de Efecto* permite a un componente [conectarse y sincronizarse con sistemas externos.](/learn/synchronizing-with-effects) Esto incluye lidiar con la red, el DOM del navegador, animaciones, *widgets* escritos utilizando una biblioteca de UI diferente y otro código que no es de React.
* [`useEffect`](/reference/react/useEffect) conecta un componente a un sistema externo.
```js
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
// ...
```
Our The React reference documentation is broken down into functional subsections:

Los *Hooks de Efecto* son una "puerta de escape" del paradigma de React. No utilices los *Efectos* para guiar el flujo de los datos de tu aplicación. Si no estás interactuando con un sistema externo, [puede que no necesites un Hook de Efecto.](/learn/you-might-not-need-an-effect)
## React {/*react*/}
Programmatic React features:
* [Hooks](/reference/react/hooks) - Use different React features from your components.
* [Components](/reference/react/components) - Documents built-in components that you can use in your JSX.
* [APIs](/reference/react/apis) - APIs that are useful for defining components.
* [Directives](/reference/react/directives) - Provide instructions to bundlers compatible with React Server Components.

Hay dos variaciones poco usadas de `useEffect` con diferencias en los tiempos en que se llaman:
* [`useLayoutEffect`](/reference/react/useLayoutEffect) se activa antes de que el navegador vuelva a pintar la pantalla. Aquí puedes hacer cálculos de maquetación (*layout*).
* [`useInsertionEffect`](/reference/react/useInsertionEffect) se activa antes de que React haga cambios en el DOM. Aquí las bibliotecas pueden insertar CSS dinámico.
---
## Hooks de rendimiento {/*performance-hooks*/}
Una forma común de optimizar el rendimiento del rerenderizado es evitar trabajo innecesario. Por ejemplo, puedes decirle a React que reutilice un cálculo guardado en caché o que se salte un rerenderizado si los datos no han cambiado desde el renderizado anterior.
Para evitar cálculos y renderizados innecesarios, usa uno de estos Hooks:
- [`useMemo`](/reference/react/useMemo) permite guardar en caché los resultados de un cálculo costoso.
- [`useCallback`](/reference/react/useCallback) permite guardar en caché una función definida antes de pasarla a un componente optimizado.
```js
function TodoList({ todos, tab, theme }) {
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
// ...
}
```
Algunas veces no podrás evitar un rerenderizado porque la pantalla realmente necesita una actualización. En ese caso, puedes mejorar el rendimiento separando las actualizaciones bloqueantes que deben ser síncronas (como al escribir dentro de una entrada de texto) de las actualizaciones no bloqueantes, que no necesitan bloquear la interfaz de usuario (como actualizar un gráfico).
Para priorizar el renderizado, usa uno de estos Hooks:
- [`useTransition`](/reference/react/useTransition) permite marcar una transición de estado como no bloqueante y permitir que otras actualizaciones la interrumpan.
- [`useDeferredValue`](/reference/react/useDeferredValue) te permite aplazar la actualización de una parte no crítica de la interfaz de usuario y dejar que otras partes se actualicen primero.
---
## Hooks de recursos {/*resource-hooks*/}
Un componente puede acceder a *recursos* sin tenerlos como parte de su estado. Por ejemplo, un componente puede leer un mensaje de una Promesa o leer información de estilo de un contexto.
Para leer un valor de un recurso, utilice este Hook:
- [`use`](/reference/react/use) te permite leer el valor de un recurso como una [Promesa](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise) o [contexto](/learn/passing-data-deeply-with-context).
```js
function MessageComponent({ messagePromise }) {
const message = use(messagePromise);
const theme = use(ThemeContext);
// ...
}
```
---
## Otros Hooks {/*other-hooks*/}
Estos Hooks son mayormente útiles para autores de bibliotecas y no son comúnmente usadas en el código de la aplicación.
- [`useDebugValue`](/reference/react/useDebugValue) permite personalizar la etiqueta que las Herramientas de Desarrollo de React muestran para tu Hook personalizado.
- [`useId`](/reference/react/useId) permite que un componente se asocie un ID único. Normalmente, se utiliza con las APIs de accesibilidad.
- [`useSyncExternalStore`](/reference/react/useSyncExternalStore) permite que un componente se subscriba a un almacenamiento (*store*) externo.
---
## React DOM {/*react-dom*/}
React-dom contains features that are only supported for web applications
(which run in the browser DOM environment). This section is broken into the following:

## Tus propios Hooks {/*your-own-hooks*/}
* [Hooks](/reference/react-dom/hooks) - Hooks for web applications which run in the browser DOM environment.
* [Components](/reference/react-dom/components) - React supports all of the browser built-in HTML and SVG components.
* [APIs](/reference/react-dom) - The `react-dom` package contains methods supported only in web applications.
* [Client APIs](/reference/react-dom/client) - The `react-dom/client` APIs let you render React components on the client (in the browser).
* [Server APIs](/reference/react-dom/server) - The `react-dom/server` APIs let you render React components to HTML on the server.

También puedes [definir tus propios Hooks personalizados](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component) como funciones JavaScript.
## Legacy APIs {/*legacy-apis*/}
* [Legacy APIs](/reference/react/legacy) - Exported from the react package, but not recommended for use in newly written code.
Loading

0 comments on commit 3f3593f

Please sign in to comment.