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 💡
`react-hooks-form` offers a `useFormContext` hook that enable custom component to work as Compound Components. So! All the time I spent with that TS thing was "waste time" (quotes since I learned a few things)
What was the solution?
Just spin off a new component that have access to the `useFormContext` and grab what I need (the errors object) and add the error handling logic there.
No more screaming from TS and the solution is simple .
An example react-hook-form.com/api/useformcon…
And if you are worry about performance:
And As I mentioned, this use of the Context API can be referenced as Compound Components and you can find an example of this in the following @eggheadio course

• • •

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!


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

6 May
State management in a web app can be a real PITA and confusing topic to tackle down.
The way that you handle the state is something you should take care of from the very beginning.

Starting for: what is state and what type of state do I have?
The application state can be split into at least two types :

🕙 Server state: asynchronous and doesn't really belongs to the app, remotely persisted, potentially out-of-date.

📺 UI state: synchronous, easily accessible, derived from user interaction. Complete ownership
Since the nature of the state is different in each case we should choose the correct tool and "architecture" to manage it.

There is a ton of solutions out there and I think that all of them are good one when used correctly.

Like Redux, RTK, zustand, Mobx, etc
Read 17 tweets
5 May
Gracias a la lamentable pandemia la educación remota es pan de cada día tanto para nuestr@s niñ@s como también para adultos buscando mejorar sus conocimientos.
Hay muchos sitios y muchas formas de ofrecer y consumir contenido pero como hacer que sea educación efectiva?
Es un mundo complejo y claramente diferente para cada uno pero creo podemos dividirlo en grupos eta ríos buscando que funciona mejor para
- preescolares (tengo mis opiniones aquí)
- adolescentes
- universidad
- Adultos buscando mejorar su carrera
Me enfocare en el último punto
Ciertamente hay muchos servicios tanto de pago como gratis incluyendo YouTube
Pero creo q la única forma de hacer que el aprendizaje sea efectivo es más allá de simplemente consumir contenido.
Y aquí es donde la forma en que sea crea el contenido para incluir acción es importante
Read 4 tweets
4 May
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.
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

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

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!