<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Kelvin Almeida</title>
    <description>The latest articles on Forem by Kelvin Almeida (@kelvgraf).</description>
    <link>https://forem.com/kelvgraf</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3117108%2F0a16b60a-d934-4354-8137-77e1312ef0dc.jpg</url>
      <title>Forem: Kelvin Almeida</title>
      <link>https://forem.com/kelvgraf</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kelvgraf"/>
    <language>en</language>
    <item>
      <title>Gerenciamento de estado no Frontend: Entendendo Context API.</title>
      <dc:creator>Kelvin Almeida</dc:creator>
      <pubDate>Thu, 08 May 2025 13:52:03 +0000</pubDate>
      <link>https://forem.com/kelvgraf/gerenciamento-de-estado-no-frontend-entendendo-context-api-55ao</link>
      <guid>https://forem.com/kelvgraf/gerenciamento-de-estado-no-frontend-entendendo-context-api-55ao</guid>
      <description>&lt;h2&gt;
  
  
  O que é o gerenciamento de estado?
&lt;/h2&gt;

&lt;p&gt;Gerenciamento de estado é o processo de controlar e gerenciar os dados de uma aplicação. No frontend, significa manter atualizada as informações que influenciam a renderização da interface. Exemplo, quando estamos digitado em um formulário, se um modal está aberto, ou quais itens estão no carrinho de compras.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  O que é estado em uma aplicação frontend?
&lt;/h2&gt;

&lt;p&gt;O estado é qualquer informação que muda com o tempo enquanto o interagimos com a aplicação. Um exemplo é o texto digitado em um campo de busca, um outro exemplo é quando clicamos em um botão e abre um modal.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Diferença entre estado local e estado global
&lt;/h2&gt;

&lt;p&gt;O estado local se limita apenas em um único componente, um botão que muda de cor quando clicamos nele.&lt;/p&gt;

&lt;p&gt;O estado global é compartilhado por multiplos componentes, dados do usuário logado acessados por toda a aplicação.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Exemplo simples com useState
&lt;/h2&gt;

&lt;p&gt;O estado &lt;code&gt;contador&lt;/code&gt; é local. Ele só afeta o componente &lt;strong&gt;Contador&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

function Contador() {
  const [contador, setContador] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Você clicou {contador} vezes&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setContador(contador + 1)}&amp;gt;Clique&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;h2&gt;
  
  
  Por que useState às vezes não é suficiente?
&lt;/h2&gt;

&lt;p&gt;Imagine agora uma aplicação com vários componentes que precisam acessar ou modificar os mesmos dados. Aí começam os problemas com useState, como passar muitas props de um componente para o outro, precisamos levantar o estado para um componente pai comum, com isso a  estrutura do código se torna difícil de escalar e manter.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Exemplo simples do problema:
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  const [usuario, setUsuario] = useState(null);

  return (
    &amp;lt;&amp;gt;
      &amp;lt;Header usuario={usuario} /&amp;gt;
      &amp;lt;Sidebar usuario={usuario} /&amp;gt;
      &amp;lt;Dashboard usuario={usuario} /&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Se você precisar modificar &lt;code&gt;usuario&lt;/code&gt; dentro de &lt;code&gt;Dashboard&lt;/code&gt;, vamos precisar passar também &lt;code&gt;setUsuario&lt;/code&gt; e dessa forma começa a bagunçar tudo em projetos maiores.&lt;br&gt;
Por isso, entram soluções como &lt;code&gt;Context API&lt;/code&gt;, &lt;code&gt;Redux&lt;/code&gt; e &lt;code&gt;Zustand&lt;/code&gt;, que resolvem esses problemas ao fornecer estado global de forma organizada.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Como a Context API resolve o problema?
&lt;/h2&gt;

&lt;p&gt;Voltando ao exemplo anterior, onde &lt;code&gt;usuario&lt;/code&gt; precisava ser passado por &lt;code&gt;props&lt;/code&gt; para vários componentes, com a Context API, podemos criar um contexto, fornecer o valor do contexto em um componente pai e consumir o valor em qualquer componente filho.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Exemplo básico com Context API
&lt;/h2&gt;

&lt;p&gt;Criando o contexto &lt;code&gt;UsuarioContext.js&lt;/code&gt; usando &lt;code&gt;createContext&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createContext } from 'react';

export const UsuarioContext = createContext(null);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Apos criar nosso contexto vamos envolver no nosso componente raiz com o &lt;code&gt;provider&lt;/code&gt;, compartilhados os dados via a propriedade &lt;code&gt;value&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.js
import { useState } from 'react';
import { UsuarioContext } from './UsuarioContext';
import Header from './Header';
import Dashboard from './Dashboard';

function App() {
  const [usuario, setUsuario] = useState({ nome: 'João' });

  return (
    &amp;lt;UsuarioContext.Provider value={{ usuario, setUsuario }}&amp;gt;
      &amp;lt;Header /&amp;gt;
      &amp;lt;Dashboard /&amp;gt;
    &amp;lt;/UsuarioContext.Provider&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Usando em qualquer componente:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//components/Header.js
import { useContext } from 'react';
import { UsuarioContext } from '../context/UsuarioContext';

function Header() {
  const { usuario } = useContext(UsuarioContext);

  return (
    &amp;lt;header&amp;gt;
      &amp;lt;p&amp;gt;Bem-vindo, {usuario.nome}!&amp;lt;/p&amp;gt;
    &amp;lt;/header&amp;gt;
  );
}

export default Header;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;h2&gt;
  
  
  Vantagens de usar Context API
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Não precisamos de bibliotecas externas, pois ela é nativa do React.&lt;/li&gt;
&lt;li&gt;Ótima para dados simples compartilhados como por exemplo, tema, idioma e autenticação. &lt;/li&gt;
&lt;li&gt;Evitamos passar props em cadeia e não vamos ter uma aplicação bagunçada.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Desvantagem e limitações
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Quando o valor de um contexto muda, todos os componentes que usam esse contexto serão re-renderizados, mesmo que só uma parte do estado tenha mudado.&lt;/li&gt;
&lt;li&gt;Falta de ferramentas de debug, middlewares e gerenciar ações assíncronas complexas como chamadas API com loading e erro, pode virar uma bagunça.&lt;/li&gt;
&lt;li&gt;Cinforme adicionamos mais Context.Providers para dividir o estado em partes menores, nossa aplicação pode começar a parecer uma bagunça de providers, exemplo:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ThemeContext.Provider&amp;gt;
  &amp;lt;IdiomaContext.Provider&amp;gt;
    &amp;lt;UsuarioContext.Provider&amp;gt;
      &amp;lt;CarrinhoContext.Provider&amp;gt;
        &amp;lt;App /&amp;gt;
      &amp;lt;/CarrinhoContext.Provider&amp;gt;
    &amp;lt;/UsuarioContext.Provider&amp;gt;
  &amp;lt;/IdiomaContext.Provider&amp;gt;
&amp;lt;/ThemeContext.Provider&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Isso pode dificultar a manutenção e leitura do código.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;O gerenciamento de estado é essencial para manter a consistência e a fluidez das nossas aplicações front-end. A Context API é uma ótima solução nativa para estados globais simples, mas se estivermos lidando com um aplicações muito grandes, complexas ou com muitas atualizações de estados, talvez seja melhor usar soluções como &lt;code&gt;Zustand&lt;/code&gt; e &lt;code&gt;Redux&lt;/code&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>pt</category>
      <category>react</category>
      <category>nextjs</category>
    </item>
    <item>
      <title>State Management in the Frontend: Understanding the Context API</title>
      <dc:creator>Kelvin Almeida</dc:creator>
      <pubDate>Thu, 08 May 2025 13:51:16 +0000</pubDate>
      <link>https://forem.com/kelvgraf/state-management-in-the-frontend-understanding-the-context-api-1hi6</link>
      <guid>https://forem.com/kelvgraf/state-management-in-the-frontend-understanding-the-context-api-1hi6</guid>
      <description>&lt;h2&gt;
  
  
  What is state management
&lt;/h2&gt;

&lt;p&gt;State management is the process of controlling and managing the data of an application. In the frontend, it means keeping the information that influences the rendering of the interface up to date. For example, when we are typing in a form, whether a modal is open, or which items are in the shopping cart.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What is state in a frontend application?
&lt;/h2&gt;

&lt;p&gt;State is any information that changes over time while interacting with the application. One example is the text typed in a search field; another example is when we click a button and a modal opens.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Difference between local state and global state
&lt;/h2&gt;

&lt;p&gt;Local state is limited to a single component, such as a button that changes color when clicked.&lt;/p&gt;

&lt;p&gt;Global state is shared by multiple components, such as user data that can be accessed throughout the application.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Simple example with useState
&lt;/h2&gt;

&lt;p&gt;The counter state is local. It only affects the Counter component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

function Counter() {
  const [counter, setCounter] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;You clicked {counter} times&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCounter(counter + 1)}&amp;gt;Click&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;h2&gt;
  
  
  Why is useState sometimes not enough?
&lt;/h2&gt;

&lt;p&gt;Now imagine an application with several components that need to access or modify the same data. This is where problems with useState begin, such as passing many props from one component to another. We need to lift the state to a common parent component, which makes the code structure hard to scale and maintain.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Simple example of the problem:
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  const [user, setUser] = useState(null);

  return (
    &amp;lt;&amp;gt;
      &amp;lt;Header user={user} /&amp;gt;
      &amp;lt;Sidebar user={user} /&amp;gt;
      &amp;lt;Dashboard user={user} /&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;If you need to modify user inside Dashboard, we will also need to pass setUser, and this is where things start to get messy in larger projects. That's why solutions like Context API, Redux, and Zustand come into play, as they solve these problems by providing global state in an organized manner.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  How does the Context API solve the problem?
&lt;/h2&gt;

&lt;p&gt;Going back to the previous example, where &lt;code&gt;user&lt;/code&gt; had to be passed through &lt;code&gt;props&lt;/code&gt; to multiple components, with the Context API, we can create a context, provide the context value in a parent component, and consume the value in any child component.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Basic example with Context API
&lt;/h2&gt;

&lt;p&gt;Creating the &lt;code&gt;UserContext.js&lt;/code&gt; context using &lt;code&gt;createContext&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createContext } from 'react';

export const UserContext = createContext(null);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After creating our context, we wrap our root component with the &lt;code&gt;provider&lt;/code&gt;, sharing the data via the &lt;code&gt;value&lt;/code&gt; property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.js
import { useState } from 'react';
import { UserContext } from './UserContext';
import Header from './Header';
import Dashboard from './Dashboard';

function App() {
  const [user, setUser] = useState({ name: 'John' });

  return (
    &amp;lt;UserContext.Provider value={{ user, setUser }}&amp;gt;
      &amp;lt;Header /&amp;gt;
      &amp;lt;Dashboard /&amp;gt;
    &amp;lt;/UserContext.Provider&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using in any component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// components/Header.js
import { useContext } from 'react';
import { UserContext } from '../context/UserContext';

function Header() {
  const { user } = useContext(UserContext);

  return (
    &amp;lt;header&amp;gt;
      &amp;lt;p&amp;gt;Welcome, {user.name}!&amp;lt;/p&amp;gt;
    &amp;lt;/header&amp;gt;
  );
}

export default Header;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;h2&gt;
  
  
  Advantages of using Context API
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We don't need external libraries since it's native to React.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Great for simple shared data such as theme, language, and authentication.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We avoid passing props in a chain, keeping the application clean and organized.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Disadvantages and limitations
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;When the value of a context changes, all components that use that context will re-render, even if only part of the state has changed.&lt;/li&gt;
&lt;li&gt;Lack of debugging tools, middlewares, and management of complex asynchronous actions such as API calls with loading and error states can become messy.&lt;/li&gt;
&lt;li&gt;As we add more Context Providers to split the state into smaller pieces, our application can start to look like a mess of providers. For example:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ThemeContext.Provider&amp;gt;
  &amp;lt;LanguageContext.Provider&amp;gt;
    &amp;lt;UserContext.Provider&amp;gt;
      &amp;lt;CartContext.Provider&amp;gt;
        &amp;lt;App /&amp;gt;
      &amp;lt;/CartContext.Provider&amp;gt;
    &amp;lt;/UserContext.Provider&amp;gt;
  &amp;lt;/LanguageContext.Provider&amp;gt;
&amp;lt;/ThemeContext.Provider&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This can make the code harder to maintain and read.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;State management is essential for maintaining consistency and smoothness in our frontend applications. The Context API is a great native solution for simple global states, but if we're dealing with very large or complex applications with many state updates, it might be better to use solutions like &lt;code&gt;Zustand&lt;/code&gt; and &lt;code&gt;Redux&lt;/code&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>en</category>
      <category>nextjs</category>
      <category>react</category>
    </item>
  </channel>
</rss>
