Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!