Do you know the state reducer pattern in React?

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

egghead.io/courses/build-…
También está disponible en español!!

egghead.io/courses/hooks-…

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Matías Hernández Arellano

Matías Hernández Arellano Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @matiasfha

4 May
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 💡
Read 7 tweets
24 Apr
When writing React.

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.
Read 9 tweets
24 Apr
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.
Read 12 tweets
22 Apr
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

egghead.io/blog/matias-he…
Becoming an instructor gave so much confident and encouragement to move forward that I now have two podcasts @cafe_contech and @ControlRemoto7 had the honor of became and @Auth0Ambassador and @MediaDevs, write for @freeCodeCamp and @freecodecampES...
Been accepted on @draftdev and been able to write for other publications (not yet published) and also land a pretty good job at @Clevertech.
Read 6 tweets
18 Apr
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
Read 14 tweets
18 Apr
¿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
Read 19 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!