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

181
Visualizações
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 à 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