Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda