He estado pensando mucho en la composición de componentes y cómo se pasa por alto esta "característica" en la mayoría de los proyectos.
React es inherentemente "componible", se puede argumentar que la composición es el punto central de React y el modelo de componentes.

Entonces, ¿por qué no se usa con más frecuencia?
Una razón podría ser que: no es el modelo mental predeterminado.
Es como si la forma predeterminada en que estructuramos componentes en nuestras mentes fuera solo herencia. Contenedores que contienen más contenedores.

Crear ese código definitivamente termina en un problema de prop drilling en algún momento.
Pero. ¿Qué es prop drilling y por qué es un problema?
Es una "característica" o capacidad de los componentes para compartir datos entre ellos.
Las props son la forma en que los componentes se comunican entre sí.

Las props son la API de tus componentes.
Entonces, prop drilling es la técnica principal para compartir datos entre componentes de padres a hijos. Pero, ¿por qué se considera un problema? Porque en algún momento el árbol de componentes está tan anidado que pasar las props es un dolor de cabeza.
Aquí es cuando deberíamos usar composición. La mayor parte de estos componente suelen ser simplemente "diseño" en lugar de lógica, por lo actúan como proxies pasando los datos al siguiente children.

@mjackson tiene una muy buen video sobre esto.
Entonces, ¿por qué no se usa composición con más frecuencia? Creo que son solo viejos hábitos que se quedaron.

Prop drilling a menudo se relaciona con la el manejo de estado y fue una gran palabra de moda cuando Flux entró en juego y luego Redux. (Viejos tiempos).
Entonces vimos una solución ahí.
Comenzamos a usar implementaciones similares a Flux moviendo todo fuera del árbol de React tratando de evitar el uso de prop drilling. Esperando replicar ese modelo de "Un componente es una función del estado".Pero nos olvidamos de la composición
Más tarde, Context se convirtió en la norma y seguimos haciendo lo mismo que antes. Mover todos los datos compartidos a una lugar global para compartirlos.
Aunque Context es increíble, en mi opinión, es una muy buena herramienta para los autores de bibliotecas, pero para los desarrolladores de aplicaciones deberíamos usar Composición con más frecuencia y, al mismo tiempo, trabajar para que el concepto conocido.
Si te gustó el contenido has RT al primer tweet :D . Gracias

• • •

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

20 May
🎉 JOB ALERT
@Clevertech is looking for experienced React Devs

Come work with an awesome and kind team (And with me 😅)

Fully remote positions with a really remote 1sr company.

If you're looking for level up your career this might be the opportunity.

Check the links below!
Do you know React and feel comfortable working with big codebases?
You enjoy working with JSX and composing hooks?
clevertech.biz/careers/senior… start date June 1st!
You know React but also feels really comfortably with node and express?
Check this out!

clevertech.biz/careers/senior…
Read 7 tweets
19 May
Been thinking a lot about component composition and how overlook this "feature" is in most codebases.

Reacr is ineheretrly composable one can argue that composition is the whole point of React and the component model.

So, why is not used more frequently?
One reason could be that: is not the default mental model.

Is like the default way we structure components in our minds is just inheritance. Containers containing more containers.

This approach of will definitely ends up in a prop drilling issue at some point.
But. What is prop drilling and why is an issue?
Prop drilling is a "feature" or at least capability of components to share data between them.
Props are the way components communicate each other. Is their API, and through this, you can pass data from a parent component.
Read 10 tweets
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 18 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
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
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

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!

:(