<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adrian Fernandez on Medium]]></title>
        <description><![CDATA[Stories by Adrian Fernandez on Medium]]></description>
        <link>https://medium.com/@adrianfdez469?source=rss-84ca5b063660------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qWClvm_pjTFklHgcoLNgDQ.jpeg</url>
            <title>Stories by Adrian Fernandez on Medium</title>
            <link>https://medium.com/@adrianfdez469?source=rss-84ca5b063660------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:59:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adrianfdez469/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Guía completa para manejar el estado en React con Zustand y TypeScript]]></title>
            <link>https://adrianfdez469.medium.com/gu%C3%ADa-completa-para-manejar-el-estado-en-react-con-zustand-y-typescript-896a6bb3e68a?source=rss-84ca5b063660------2</link>
            <guid isPermaLink="false">https://medium.com/p/896a6bb3e68a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Adrian Fernandez]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 16:01:46 GMT</pubDate>
            <atom:updated>2024-10-16T16:01:46.718Z</atom:updated>
            <content:encoded><![CDATA[<p>En el ecosistema de React, existen muchas formas de manejar el estado global. Herramientas como Redux y Context API son muy populares, pero a menudo implican una configuración excesiva. <strong>Zustand</strong> es una alternativa ligera, rápida y fácil de usar que destaca por su simplicidad. En esta guía, aprenderás a integrar <strong>Zustand</strong> con <strong>TypeScript</strong> para aprovechar al máximo ambas tecnologías.</p><h3>¿Qué es Zustand?</h3><p><strong>Zustand</strong> es una librería pequeña pero poderosa para gestionar el estado global en aplicaciones React. Creada por los desarrolladores de <a href="https://github.com/pmndrs">Poimandres</a>, quienes también han desarrollado herramientas populares como react-three-fiber, Zustand proporciona una API intuitiva para trabajar con el estado sin la sobrecarga de librerías más complejas como Redux.</p><h3>¿Por qué Zustand?</h3><p><strong>Zustand</strong> ofrece varias ventajas que la hacen sobresalir en comparación con otras librerías de gestión de estado:</p><ul><li><strong>Ligera y rápida</strong>: No afecta el rendimiento de tu aplicación.</li><li><strong>Simple de usar</strong>: Sin necesidad de configurar reducers, acciones o middlewares complejos.</li><li><strong>Compatible con TypeScript</strong>: Estado seguro y tipado gracias a su integración nativa con TypeScript.</li><li><strong>Escalable</strong>: Perfecta para proyectos pequeños y grandes.</li></ul><p>En este tutorial, exploraremos cómo usar <strong>Zustand</strong> con <strong>TypeScript</strong> en una aplicación de React.</p><h3>Instalación</h3><p>Lo primero es instalar la librería:</p><pre>npm install zustand</pre><p>O con yarn:</p><pre>yarn add zustand</pre><p>Si trabajas con <strong>TypeScript</strong>, no necesitas instalar tipos adicionales, ya que Zustand viene con soporte para TypeScript.</p><h3>Crear un almacén en Zustand con TypeScript</h3><p>El estado en Zustand se organiza en un “almacén” (store), que contiene tanto el estado como las acciones que lo modifican. Vamos a crear un almacén simple que mantenga el estado de un contador y acciones para incrementarlo y reducirlo.</p><h3>Definiendo el tipo del estado</h3><p>Primero, definimos los tipos de nuestro estado y las acciones:</p><pre>// Definición del tipo del estado<br>interface CounterState {<br>  count: number;<br>  increase: () =&gt; void;<br>  decrease: () =&gt; void;<br>}</pre><p>Este tipo incluye una propiedad count que será un número, y dos acciones (increase y decrease) que serán funciones para actualizar el estado.</p><h3>Crear el almacén con Zustand</h3><p>Ahora, vamos a crear el almacén usando Zustand:</p><pre>import create from &#39;zustand&#39;;<br><br>const useStore = create&lt;CounterState&gt;((set) =&gt; ({<br>  count: 0, // Estado inicial<br>  increase: () =&gt; set((state) =&gt; ({ count: state.count + 1 })),<br>  decrease: () =&gt; set((state) =&gt; ({ count: state.count - 1 })),<br>}));<br><br>export default useStore;</pre><p>Aquí estamos usando el generador create de Zustand y pasando el tipo CounterState para asegurar que todo el estado y las acciones estén correctamente tipadas.</p><h3>Usar el almacén en un componente</h3><p>Ahora que tenemos el almacén, podemos utilizarla en nuestros componentes de React.</p><h3>Counter.tsx</h3><pre>import React from &#39;react&#39;;<br>import useStore from &#39;./useStore&#39;;<br><br>const Counter: React.FC = () =&gt; {<br>  const { count, increase, decrease } = useStore();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Contador: {count}&lt;/h1&gt;<br>      &lt;button onClick={increase}&gt;Incrementar&lt;/button&gt;<br>      &lt;button onClick={decrease}&gt;Disminuir&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Counter;</pre><p>En este componente:</p><ul><li><strong>count</strong> es el estado que estamos leyendo desde la tienda.</li><li><strong>increase y </strong><strong>decrease</strong> son las acciones para modificar el estado.</li></ul><h3>Estados derivados y computados</h3><p>Zustand permite crear estados derivados que dependen de otros valores del estado. Imagina que queremos mostrar un mensaje cuando el contador sea negativo:</p><h3>Modificar useStore.ts</h3><pre>interface CounterState {<br>  count: number;<br>  isNegative: boolean;<br>  increase: () =&gt; void;<br>  decrease: () =&gt; void;<br>}<br><br>const useStore = create&lt;CounterState&gt;((set) =&gt; ({<br>  count: 0,<br>  isNegative: false, // Estado derivado<br>  increase: () =&gt;<br>    set((state) =&gt; ({<br>      count: state.count + 1,<br>      isNegative: state.count + 1 &lt; 0,<br>    })),<br>  decrease: () =&gt;<br>    set((state) =&gt; ({<br>      count: state.count - 1,<br>      isNegative: state.count - 1 &lt; 0,<br>    })),<br>}));</pre><p>En este caso, isNegative es un estado derivado que cambia automáticamente cuando count es menor que 0.</p><h3>Modificar Counter.tsx</h3><pre>const Counter: React.FC = () =&gt; {<br>  const { count, increase, decrease, isNegative } = useStore();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Contador: {count}&lt;/h1&gt;<br>      {isNegative &amp;&amp; &lt;p&gt;El contador es negativo&lt;/p&gt;}<br>      &lt;button onClick={increase}&gt;Incrementar&lt;/button&gt;<br>      &lt;button onClick={decrease}&gt;Disminuir&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Manejo de estados complejos</h3><p>Zustand también puede manejar objetos y arrays como parte del estado. Vamos a crear una lista de tareas (to-do list) como ejemplo.</p><h3>useStore.ts (lista de tareas):</h3><pre>interface TaskState {<br>  tasks: string[];<br>  addTask: (task: string) =&gt; void;<br>  removeTask: (task: string) =&gt; void;<br>}<br><br>const useStore = create&lt;TaskState&gt;((set) =&gt; ({<br>  tasks: [],<br>  addTask: (task) =&gt; set((state) =&gt; ({ tasks: [...state.tasks, task] })),<br>  removeTask: (task) =&gt;<br>    set((state) =&gt; ({<br>      tasks: state.tasks.filter((t) =&gt; t !== task),<br>    })),<br>}));</pre><h3>TaskList.tsx</h3><pre>import React, { useState } from &#39;react&#39;;<br>import useStore from &#39;./useStore&#39;;<br><br>const TaskList: React.FC = () =&gt; {<br>  const { tasks, addTask, removeTask } = useStore();<br>  const [newTask, setNewTask] = useState(&#39;&#39;);<br><br>  const handleAddTask = () =&gt; {<br>    addTask(newTask);<br>    setNewTask(&#39;&#39;);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        value={newTask}<br>        onChange={(e) =&gt; setNewTask(e.target.value)}<br>        placeholder=&quot;Nueva tarea&quot;<br>      /&gt;<br>      &lt;button onClick={handleAddTask}&gt;Agregar tarea&lt;/button&gt;<br><br>      &lt;ul&gt;<br>        {tasks.map((task, index) =&gt; (<br>          &lt;li key={index}&gt;<br>            {task} &lt;button onClick={() =&gt; removeTask(task)}&gt;Eliminar&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default TaskList;</pre><h3>Persistencia de estado con middleware</h3><p>Zustand incluye soporte para middleware, como la persistencia del estado en localStorage. Vamos a ver cómo persistir el valor de un contador entre recargas de página.</p><h3>useStore.ts con persistencia:</h3><pre>import create from &#39;zustand&#39;;<br>import { persist } from &#39;zustand/middleware&#39;;<br><br>interface CounterState {<br>  count: number;<br>  increase: () =&gt; void;<br>  decrease: () =&gt; void;<br>}<br><br>const useStore = create&lt;CounterState&gt;(<br>  persist(<br>    (set) =&gt; ({<br>      count: 0,<br>      increase: () =&gt; set((state) =&gt; ({ count: state.count + 1 })),<br>      decrease: () =&gt; set((state) =&gt; ({ count: state.count - 1 })),<br>    }),<br>    {<br>      name: &#39;counter-storage&#39;, // Nombre en localStorage<br>    }<br>  )<br>);<br><br>export default useStore;</pre><p>Con esta configuración, el estado del contador se guardará automáticamente en el localStorage, y cuando recargues la página, se restaurará su valor anterior.</p><h3>Conclusión</h3><p>Zustand es una excelente opción para manejar el estado en aplicaciones React, y su integración con TypeScript la convierte en una opción aún más atractiva. Es simple, ligera, y perfecta tanto para aplicaciones pequeñas como para proyectos más grandes.</p><p>Si estás buscando una alternativa fácil a Redux o quieres algo más sencillo que Context API, ¡prueba <strong>Zustand</strong> en tu próximo proyecto!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=896a6bb3e68a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep React Child State on the Child! If Possible.]]></title>
            <link>https://adrianfdez469.medium.com/keep-react-child-state-on-the-child-if-possible-d531f0715408?source=rss-84ca5b063660------2</link>
            <guid isPermaLink="false">https://medium.com/p/d531f0715408</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Adrian Fernandez]]></dc:creator>
            <pubDate>Fri, 07 May 2021 03:26:06 GMT</pubDate>
            <atom:updated>2021-05-12T00:29:29.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Simple Way to Get Child State in the Parent Component Without Unnecessary Renders</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*HUZpwlZ9wYynlyBh__rDUw.jpeg" /></figure><p>Fare warning: You need to know about <a href="https://es.reactjs.org/">React </a>to understand this post. The problems and solutions exposes here are all using the modern react approach: <a href="https://es.reactjs.org/docs/hooks-intro.html">Hooks</a>.</p><p>This Post is for all those <a href="https://es.reactjs.org/">React </a>programmers that have been cross with one particular situation.</p><p>The problem:</p><p>Imagine your are building a parent component (lets call it “PARENT”), and inside that parent component you have a child component (lets call it “CHILD”). The “PARENT” component has a button, that when it’s clicked, you have to collect the internal state of “PARENT” and “CHILD” components to do something with it, like send the data/state to POST API endpoint to save it on a data base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*Tyn8P28ZkhJWy38XsgznlQ.png" /></figure><p>Possible solutions:</p><p>1- <strong>Elevating the state</strong>: The most common solution is to manage the state of the “CHILD” in the “PARENT” component, so in “PARENT” you have to manage it’s own state and his “CHILD” state. This can be a problem, because you are coupling this components and overloads the responsibility and state management on the “PARENT” component, making it more difficult to test, re-use and maintain.</p><p>2- <strong>Global State</strong>: Uses some mechanism to manage all the state from a third party library such as <a href="https://es.redux.js.org/">Redux </a>or using <a href="https://reactjs.org/docs/context.html">Context</a>. With this approach we remove the problems from the first solution, because it elevates the state management to a global place, but if we need to know the state of “CHILD” inside “PARENT” component, we need to subscribe “PARENT” to the global state that manage the “CHILD” state component, and while we do that, we create a more complex code, leaving one problem that where present on the first approach too: Every time the “CHILD” component change it’s state, the “PARENT” component will re-render too, and if you are not careful, all his children&#39;s will re-render as well (you can avoid that last part with <a href="https://es.reactjs.org/docs/react-api.html#reactmemo">React.memo()</a> on other children&#39;s, but that is for other post).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*GCWoDSd_SOYJUqCCc6jKLA.gif" /><figcaption>See how the parent component renders when the child changes his state. Observe the counter on the text inputs.</figcaption></figure><h3><strong>The solution to the rescue:</strong></h3><p>For this particular situation, the “CHILD” component should manage its own state, and in a particular moment, the “PARENT” must have access to that “CHILD” state, but when the “CHILD” state changes, it can’t trigger a re-render on the “PARENT” component. Achieving that, all our problems would be solved. <strong>The good news is that we can!</strong></p><h4>How to do it with a different approach?</h4><p><strong>3- Using references:</strong> To solve this, we are going to use <a href="https://reactjs.org/docs/hooks-intro.html">Hooks</a> and <a href="https://reactjs.org/docs/forwarding-refs.html">fordwardRef</a>. <em>It’s necessary that in order to work, you need React ≥v16.8.</em> If you are not familiar with <a href="https://es.reactjs.org/docs/hooks-intro.html">Hooks</a>, you should give it a try.</p><p>What we need to do in the “PARENT” is to pass a reference (lets call it “childStateRef”) to the “CHILD” component via props. That reference needs to be created on “PARENT” using the <a href="https://es.reactjs.org/docs/hooks-reference.html#useref">useRef() hook</a>. That “childStateRef” is going the be the one that will have the “CHILD” state whenever we need it on the “PARENT” component. See the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*dYQ8T_mirV__xxKDebSyIw.png" /><figcaption>The “childStateRef” is passed via props to “CHILD” and used on getChildState function to get the state of “CHILD” on a button click event.</figcaption></figure><p>On the “CHILD” component, making use of a combination with <a href="https://reactjs.org/docs/forwarding-refs.html">React.fordwardRef</a> and the <a href="https://es.reactjs.org/docs/hooks-reference.html#useimperativehandle">useImperativeHandle() hook</a> we have a way of provide to the received reference a method that returns the internal state of the “CHILD” component. See the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*tNPuD5vIir-mbisfN2hWlg.png" /><figcaption>The reference (_ref) on the “CHILD” received from the “PARENT” through React.fordwardRef() and the useImperativeHandle() Hook to allow get the state from the “PARENT”.</figcaption></figure><p><strong>This is it, We did it!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*z8SAn0tKC-2_DBnKwTrhSw.gif" /><figcaption>Applying the third solution. Note that the “PARENT” doesn’t render when the “CHILD” changes its state. Observe the counter on the text inputs</figcaption></figure><p>The code shown until now is a simple way to resolve this problem , but is not the real code used on the examples showed on animated gif. If you want to see the real code you can check this GitHub repository.</p><p><a href="https://github.com/adrianfdez469/keep-react-child-state-on-child">adrianfdez469/keep-react-child-state-on-child</a></p><p>And if you want to see the entire application running with all the three examples, and without fork or pull the the entire code and running it yourself on your local environment, you can check this link where it is deployed. Tip: Check your developer console, it will help you to see the amount of renders on each component for each of the three solutions.</p><p><a href="https://adrianfdez469.github.io/keep-react-child-state-on-child/">React App</a></p><p><strong>Conclusions</strong></p><p>In my personal opinion, this last proposal solution is the best option for some specific situations, because it avoids unnecessary renders mainly on the parent, and when we have heavy components, this can be a huge performance improvement. Also, with this last approach, you can let the state management of each component on the component itself, allowing you to have a cleaner code to test, maintain, read and understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d531f0715408" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>