Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
React - Running side effects inside pure functions

Introduction

My current use case requires to store the most fresh state updates in a cache. As state updates are async, and there can be a lot of components updating the same one in parallel, it might be a good option to store them inside the body of the useState or useReducer pure functions.

But... side effects come, and the frustration start. I have tried to await dispatches, creating custom hooks "useReducerWithCallback", and other stuff, but I don't see the correct solution to my problem.

Problem

I have a module usersCache.js which provides me with the necessary methods to make modifications to my cache:

const cache = {};

export const insert = (id, data) => ...

export const get = (id) => ...

// and more stuff

I am trying to update this cache when I make state updates. For example:

 const currentUser = useContext(CurrentUserContext);
 
 ...

 // Note: setData is just the state setter useState hook
 currentUser.setData((prevData) => {
     const newTotalFollowing = prevData.totalFollowing + 1;

     usersCache.update(currentUser.data.id, { newTotalFollowing }); <---- SIDE EFFECT
     
     return { ...prevData, totalFollowing: newTotalFollowing };
 });

And same stuff in my otherUsers reducer

import { usersCache } from "../../services/firebase/api/users"

export default (otherUsers, action) => {   
    switch (action.type) {
       case "follow-user": {
          const { userId, isFollowing } = action;

          const prevUserData = otherUsers.get(userId);

          const newTotalFollowers = prevUserData.totalFollowers + (isFollowing ? 1 : -1);

          usersCache.update(userId, { totalFollowers: newTotalFollowers }); // merge update

          return new Map([
             ...otherUsers,
            [
                userId,
                {
                   ...prevUserData,
                   totalFollowers: newTotalFollowers
                 ]
            ]
         );
       }

       ...
    }
}

As in pure functions we shouldn't perform side effects... Is there any other approach to handle this?

Note: I am not using Redux

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can check this full working example using the repository pattern and react hooks to simplify async actions with state dispatches. I know you are not using redux but you can adapt this example using the useReducer hook to connect it to your React Context store.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda