Search code examples
reactjsuse-effect

When to fetch data and when to update state?


I don't know if there is a best practice that is accepted for this. I have a component which fetches data inside useEffect using axios and updates the state (setData) based on the response. Response returns an array of objects, i.e:

[
  {"title" : "Foo", "value":1},
  {"title" : "Bar", "value": 2}
]

User is allowed to delete an item from the list. When user deletes an item, I send a DELETE request using axios, but I also update the state like this:

setData(data.filter(d => d.id !== item.id))

which re-renders the component and the item is gone. I wonder whether this shouldn't be done by updating the state but rather using useEffect to fetch the data, and waiting for backend to send the response.

Is there a best way performance-wise?


Solution

  • The only problem here is what happens on server's error.

    Therefore having a middleware or updating the state on success will ensure the component have the most updated data.

    // No middleware
    axios.delete(url).then(() => setState(...));
    
    // Middleware
    axios.delete(url).then(() => updateStore(...));
    // ... Component listening to store updates
    

    As a rule of thumb, you shouldn't duplicate the state (in this case you handle the state twice - one which you fetch and one in the component), so I highly recommend not use this pattern although it gives a little faster UI feedback (use it when you are optimistic and server is slow).

    // optimistic
    setData(data.filter(d => d.id !== item.id))
    axios.delete(url).catch(() => setState(prevStateBeforeError));