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
But in the past, there was a tendency to maybe overuse some tools forcing them to work for every possible case bending the solution to manage the different natures of the state.
We were all there at some point when we had all the state inside one huge Redux global state.
But we can do better!.
React is a state management solution by itself!
I'm not the only one how said so
And this tool is meant to manage your UI state by using different techniques as prop-drilling, local state, and Context.
By differentiating the UI state vs Server state and using React itself to manage the UI state we solve one piece of the puzzle. What we can do for the rest?
The server state is a different beast to tame.
When dealing with async and remote data you have multiple "inner state"
Since you are requesting data from an external source the request can be at least in the following states: idle, loading, failed, or succeed
An for sure you can manage that different states with just React hooks as you can see here
And that works!, but there is a ton of other cases that are not handled by that, like What happens if you need to fetch the same data? This solution can cache so will request it again.
Can you do optimistic updates? Yeah, you can but you need to craft that by yourself.
So, in this case, we should choose a 3rd party library, and as I said before there is a ton of possibilities. For this case, the main options are React Query and SWR
I choose React Query by @tannerlinsley
What is RQ? is a Cache Layer for your app.
It doesn't care from where the data come, the important part is that works with any Promise based request!
The principle of the RQ architecture is the encapsulation of business logic by extracting the data fetching ceremony to custom hooks.
How react-query works?
In a nutshell, you have two hooks `useQuery` and `useMutation` that do the heavy lifting for you. Those hooks will take care of managing the fetch and the promises states and will return a few booleans that let you know what happens.
Don't worry about the booleans there, is a state machine under the hood.
Also, since react-query works as a cache your data will live under a query key that you can build by passing a string or an array to the hooks.
From here you can go to the next step, like implementing optimistic updates as is shown here
But why choose React-query?
This is what you can find in this article for @clevertech where we go deeper on the react-query functionality and the: why we choose it as our server state management solution.
btw we are hiring, check clevertech.biz/careers if you want to join us and do fun, exciting, and challenging projects while working fully and worldwide remote.
And if you liked this thread, please share the first tweet, and follow me for more content about React, web dev, and dev soft skills.
And if you prefer to read the thread in a different medium or share it in other platform here you can find the unrolled version of it threadreaderapp.com/thread/1390392…
• • •
Missing some Tweet in this thread? You can try to
force a refresh
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
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 💡
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.
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