Is a design pattern that enable the user of a component to manipulate or manage the inner state of it by using a reducer pattern.
When creating components for an UI library for your project you have to take some decisions and assumptions about the way it work or be used.
But adding so many opinions to it can decrease the generalization of your component and the usability of the same.
The State Reducer Pattern (an idea an implementation by @kentcdodds for downshift) is a form of Inversion of Control where your component enable the user of it to control internal behavior through the API.
React hooks made the implementation of this pattern slightly simpler and idiomatic by using the useReducer hook.
I invite you to check this lesson on @eggheadio where I show you how to implement state reducer in a Wizard component egghead.io/lessons/react-…
That lesson is part of a course: Build Advanced Components with React Hooks
Is a community resource so you can watch it for Free
Just in case you are falling into a dark and deep TS rabbit hole with react-hooks-form.
If you want to have custom components that do something based on the `errors` that comes out of `useForm`.
That error object type is DeepMap<TFieldValue, FieldErrors>.
For some reason that I'm not in the mood to discuss xD I wanted to pass that errors down to a "generic" Input and friends component to show some error state.
But TS didn't like it. It said that I wasn't able to access `errors?.[props.name]` 😅
So I tried to bend the type system and I didn't actually fully accomplish that goal and the solution I had was really hacky and disgusting 🤮. And after digging in the code I had a bulb moment 💡
How do you decide to use useReducer instead of useState?
In general you can always use reducers, technically useState is a simplified version of useReducer.
But then, Why use useReducer?
Although it looks more complex, using it gives you great advantages.
The first advantage is encapsulation and abstraction.
useReducer uses a reducer function that lives outside of the component and is not affected by re-renders. It also simplifies your code by ISOLATING the state logic in a function.
Another advantage is that you can handle more complex states with different update logics and in an "atomic" way.
The reducer function receives the current state and an object that we commonly call an action.
Depending on the action, the function will return a new state.
Al escribir componentes React.
¿Cuando decides usar useReducer en vez de useState?
En general puedes usar reducers siempre, técnicamente useState es una versión simplificada de useReducer.
¿Por que usar useReducer?
Si bien se ve más complejo usarlo te da grandes ventajas
La primera ventaja es encapsulacion y abstracción.
useReducer utiliza una función reducer que vive fuera del componente no siendo afectada por los re-renders y además simplifica tu código por que AISLA la lógica de estado en una función.
Otra ventaja es que puedes manejar estados más complejos con lógicas de actualización diferente y de manera "atómica".
La función reducer recibe el estado actual y un objeto que comúnmente llamamos acción.
Dependiendo de la acción la función retornará un nuevo estado.
Becoming an @eggheadio instructor is for sure the biggest achievement in my career as dev.
I was just talking about this very same topic with @RealChrisSean and now I see that I been featured
Hablemos de "State management" y porqué es "complejo".
¿Que es el estado de una App?
En una versión muy simple estado son datos que cambian en el tiempo y que usamos para definir que se muestra o no al usuario.
Pero: ¿de donde vienen esos datos?
Esta pregunta es quiza la "piedra angular" para un modelo mental sobre el manejo de estado.
No todo el estado es igual ni proviene de las mismas fuentes.
Podemos definir a lo menos 2 categorías de estado
- UI state
- Server State
(shouts @tannerlinsley for this idea)
UI State: el estado que representa aspectos de la interfaz exclusivamente y que es modificado por acciones del usuario por ejemplo ejemplo un modal abierto/cerrado, el valor de un input o un menú.
Es un estado de fácil acceso, efímero y sincrono y es "simple" de manejar
¿Por que el desarrollo web se ha vuelto tan complejo?
En mi opinión tiene que ver con principalmente dos razones: 1. Los requerimientos han crecido y las expectativas de los usuarios y clientes han aumentado respecto a que es y no posible "en la plataforma"
...
2. La web (como la ideó Sir @timberners_lee) no fue ni está "arquitecturada" (palabra inventada) para lo que la estamos usando hoy.
La web fue ideada e implementada como una plataforma para compartir documentos de hiper texto. "Documentos" (subrayo ésto) que se enlazan con otros
He ahí que el lenguaje principal de la web sea HTML. Javascript vino a ser un parche sobre los motores de los browsers para darle algo de interactividad y dinamismo a esos documentos