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

169
Vistas
React: Is it a good practice to handle state updates in a service function?

Taking as an example a dummy Blog app where posts are displayed on the page.

At some point, you can update a post body. The code I would produce would look like that:

// services
import { updatePost } from './postServices.js';

const Blog = () => {
  const [posts, setPosts] = useState([]);

  ...

  const handleUpdatePost = (newBody) => {
    updatePost(postId, newBody posts, setPosts)
      .catch((error) => // handle error )
  };

  ...

  return (
    ...
  )

};

Where the updatePost function would look like that:

export const updatePost = async (postId, newBody, posts, setPosts) => {
  const result = await axios.post(`posts/${postId}`, { body: newBody });
  
  // handling the state update here
  const { updatedPost } = result.data;
  const copyPosts = [...posts];
  const post = copyPosts.find((post) => post.id === updatedPost.id);
  post.body = updatedPost.body;
  setPosts(copyPosts);
};

I like this approach because it keeps the react component clean and easily understandable. On the other hand, it requires passing the entire posts array and its setState, which I heard might not be too good (for performance reasons?).

My question is: would that code be considered as good or are there any pitfalls that I don't understand?

about 4 years ago · Juan Pablo Isaza
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