You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/blog/2018-06-07-you-probably-dont-need-derived-state.md
+1-1Lines changed: 1 addition & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -213,7 +213,7 @@ To recap, when designing a component, it is important to decide whether its data
213
213
Instead of trying to **"mirror" a prop value in state**, make the component **controlled**, and consolidate the two diverging values in the state of some parent component. For example, rather than a child accepting a "committed" `props.value` and tracking a "draft" `state.value`, have the parent manage both `state.draftValue` and `state.committedValue` and control the child's value directly. This makes the data flow more explicit and predictable.
214
214
215
215
For **uncontrolled** components, if you're trying to reset state when a particular prop (usually an ID) changes, you have a few options:
216
-
***Recomendation: To reset _all internal state_, use the `key` attribute.**
216
+
***Recommendation: To reset _all internal state_, use the `key` attribute.**
217
217
* Alternative 1: To reset _only certain state fields_, watch for changes in a special property (e.g. `props.userID`).
218
218
* Alternative 2: You can also consider fall back to an imperative instance method using refs.
#### Bailing out of a state update {#bailing-out-of-a-state-update}
92
+
#### Evitar una actualización del estado {#bailing-out-of-a-state-update}
94
93
95
-
If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the [`Object.is` comparison algorithm](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description).)
94
+
Si se actualiza un Hook de estado con el mismo valor que el estado actual, React evitará la renderización de los hijos y disparar los efectos. (React utiliza el [algoritmo de comparación `Object.is`](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/is#Description)).
96
95
97
96
### `useEffect` {#useeffect}
98
97
@@ -132,7 +131,7 @@ Sin embargo, no todos los efectos pueden ser diferidos. Por ejemplo, una mutaci
132
131
133
132
Aunque `useEffect` se aplaza hasta después de que el navegador se haya pintado, se garantiza que se activará antes de cualquier nuevo render. React siempre eliminará los efectos de un render anterior antes de comenzar una nueva actualización.
134
133
135
-
#### Condicionalmente disparando un efecto. {#conditionally-firing-an-effect}
134
+
#### Disparar un efecto condicionalmente. {#conditionally-firing-an-effect}
136
135
137
136
El comportamiento predeterminado para los efectos es ejecutar el efecto después de cada render completo. De esa manera, siempre se recrea un efecto si cambia uno de sus inputs.
Una alternativa a [`useState`](#usestate). Acepta un reducer de tipo `(state, action) => newState` y devuelve el estado actual emparejado con un método` dispatch`. (Si está familiarizado con Redux, ya sabe cómo funciona).
184
183
185
-
`useReducer`is usually preferable to `useState`when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. `useReducer`also lets you optimize performance for components that trigger deep updates because [you can pass `dispatch`down instead of callbacks](/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down).
184
+
`useReducer`a menudo es preferible a `useState`cuando se tiene una lógica compleja que involucra múltiples subvalores o cuando el próximo estado depende del anterior. `useReducer`además te permite optimizar el rendimiento para componentes que activan actualizaciones profundas, porque [puedes pasar hacia abajo `dispatch`en lugar de *callbacks*](/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down).
186
185
187
-
Here's the counter example from the [`useState`](#usestate) section, rewritten to use a reducer:
186
+
Aquí está el ejemplo del contador de la sección [`useState`], reescrito para usar un reductor:
188
187
189
188
```js
190
189
constinitialState= {count:0};
@@ -212,9 +211,9 @@ function Counter({initialCount}) {
212
211
}
213
212
```
214
213
215
-
#### Specifying the initial state {#specifying-the-initial-state}
214
+
#### Especificar el estado inicial {#specifying-the-initial-state}
216
215
217
-
There’s two different ways to initialize `useReducer` state. You may choose either one depending on the use case. The simplest way to pass the initial state as a second argument:
216
+
Hay dos formas diferentes de inicializar el estado de `useReducer`. Puedes elegir uno dependiendo de tu caso de uso. La forma más simple para pasar el estado inicial es como un segundo argumento:
218
217
219
218
```js{3}
220
219
const [state, dispatch] = useReducer(
@@ -223,17 +222,17 @@ There’s two different ways to initialize `useReducer` state. You may choose ei
223
222
);
224
223
```
225
224
226
-
>Note
225
+
>Nota
227
226
>
228
-
>React doesn’t use the `state = initialState`argument convention popularized by Redux. The initial value sometimes needs to depend on props and so is specified from the Hook call instead. If you feel strongly about this, you can call`useReducer(reducer, undefined, reducer)`to emulate the Redux behavior, but it's not encouraged.
227
+
>React no utiliza la convención del argumento `state = initialState`popularizada por Redux. El valor inicial a veces necesita tener una dependencia en las props y por tanto se especifica en cambio en la llamada al Hook. Si te parece muy importante, puedes llamar a`useReducer(reducer, undefined, reducer)`para emular el comportamiento de Redux, pero no se recomienda
You can also create the initial state lazily. To do this, you can pass an `init`function as the third argument. The initial state will be set to`init(initialArg)`.
231
+
También puedes crear el estado inicial de manera diferida. Para hacerlo, le puedes pasar una función `init`como tercer argumento. El estado inicial será establecido como`init(initialArg)`.
233
232
234
-
It lets you extract the logic for calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action:
233
+
Esto te permite extraer la lógica para calcular el estado inicial fuera del reductor. También es útil para reiniciar el estado luego en respuesta a una acción:
235
234
236
-
```js{1-3,11-12,21,26}
235
+
```js{1-3,11-12,19,24}
237
236
function init(initialCount) {
238
237
return {count: initialCount};
239
238
}
@@ -247,9 +246,7 @@ function reducer(state, action) {
247
246
case 'reset':
248
247
return init(action.payload);
249
248
default:
250
-
// Un reducer siempre debe devolver un estado válido.
251
-
// Alternativamente, puede lanzar un error si se envía una acción no válida.
252
-
return state;
249
+
throw new Error();
253
250
}
254
251
}
255
252
@@ -269,11 +266,9 @@ function Counter({initialCount}) {
269
266
}
270
267
```
271
268
272
-
#### Bailing out of a dispatch {#bailing-out-of-a-dispatch}
273
-
274
-
If you return the same value from a Reducer Hook as the current state, React will bail out without rendering the children or firing effects. (React uses the [`Object.is` comparison algorithm](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description).)
269
+
#### Evitar un *dispatch* {#bailing-out-of-a-dispatch}
275
270
276
-
`useReducer` suele ser preferible a `useState` cuando tiene una lógica de estado compleja que involucra múltiples subvalores. También le permite optimizar el rendimiento de los componentes que activan actualizaciones profundas porque [puede pasar `dispatch` en lugar de callbacks](/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down).
271
+
Si devuelves el mismo valor del estado actual desde un Hook reductor, React evitará el renderizado de los hijos y disparar efectos. (React utiliza el [algoritmo de comparación `Object.is`](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/is#Description)).
277
272
278
273
### `useCallback` {#usecallback}
279
274
@@ -302,15 +297,15 @@ Pase un callback en línea y un arreglo de entradas. `useCallback` devolverá un
Retorna un valor [memorizado](https://en.wikipedia.org/wiki/Memoization).
300
+
Devuelve un valor [memorizado](https://en.wikipedia.org/wiki/Memoization).
306
301
307
-
Pase una función de "crear" y un arreglo de entradas. `useMemo` solo volverá a calcular el valor memorizado cuando una de las entradas haya cambiado. Esta optimización ayuda a evitar cálculos costosos en cada render.
302
+
Pasa una función de "crear" y un arreglo de entradas. `useMemo` solo volverá a calcular el valor memorizado cuando una de las entradas haya cambiado. Esta optimización ayuda a evitar cálculos costosos en cada render.
308
303
309
304
Recuerde que la función pasada a `useMemo` se ejecuta durante el renderizado. No hagas nada allí que normalmente no harías al renderizar. Por ejemplo, los efectos secundarios pertenecen a `useEffect`, no a` useMemo`.
310
305
311
306
Si no se proporciona un arreglo, se calculará un nuevo valor cada vez que se pase una nueva instancia de función como primer argumento. (Con una función en línea, en cada render).
312
307
313
-
**Puede confiar en `useMemo` como una optimización del rendimiento, no como una garantía semántica.** En el futuro, React puede elegir "olvidar" algunos valores previamente memorizados y recalcularlos en el próximo render, por ejemplo. para liberar memoria para componentes fuera de pantalla. Escriba su código para que aún funcione sin `useMemo` - y luego agréguelo para optimizar el rendimiento.
308
+
**Puede confiar en `useMemo` como una optimización del rendimiento, no como una garantía semántica.** En el futuro, React puede elegir "olvidar" algunos valores previamente memorizados y recalcularlos en el próximo renderizado, por ejemplo para liberar memoria para componentes fuera de pantalla. Escribe tu código para que aún funcione sin `useMemo` - y luego agrégalo para optimizar el rendimiento.
314
309
315
310
> Nota
316
311
>
@@ -322,9 +317,9 @@ Si no se proporciona un arreglo, se calculará un nuevo valor cada vez que se pa
322
317
constrefContainer=useRef(initialValue);
323
318
```
324
319
325
-
`useRef`returns a mutable ref object whose `.current`property is initialized to the passed argument (`initialValue`). The returned object will persist for the full lifetime of the component.
320
+
`useRef`devuelve un objeto *ref* mutable cuya propiedad `.current`se inicializa con el argumento pasado (`initialValue`). El objeto devuelto se mantendrá persistente durante la vida completa del componente.
326
321
327
-
A common use case is to access a child imperatively:
322
+
Un caso de uso común es para acceder a un hijo imperativamente:
328
323
329
324
```js
330
325
functionTextInputWithFocusButton() {
@@ -403,15 +398,9 @@ function useFriendStatus(friendID) {
403
398
404
399
> Consejo
405
400
>
406
-
<<<<<<< HEAD
407
-
> No recomendamos agregar valores de depuración a cada Hook personalizado. Es más valioso para los Hooks personalizados que forman parte de las bibliotecas compartidas.
408
-
=======
409
-
> We don't recommend adding debug values to every custom Hook. It's most valuable for custom Hooks that are part of shared libraries.
> No recomendamos agregar valores de depuración a cada Hook personalizado. Es más valioso para los Hooks personalizados que forman parte de bibliotecas compartidas.
413
402
414
-
#### Aplazar el formato de los valores de depuración
403
+
#### Aplazar el formato de los valores de depuración {#defer-formatting-debug-values}
415
404
416
405
En algunos casos, formatear un valor para mostrar puede ser una operación costosa. También es innecesario a menos que un Hook sea realmente inspeccionado.
0 commit comments