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?