Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux - quick flash of previous state before dispatch issue

I'm building a React + Redux app with a Node.js backend, and one of the features is that a user can view profiles of other users. To do this, I have a section in the Redux state called users that looks like:

{
    ...,
    users: {
        user: {},
        isLoading: true
    }
}

Every time the /users/:id route is rendered, a getUser(id) action is dispatched and fills the state with the received information.

The main issue is when a user views user1's profile page (therefore redux state is now filled with user1's profile) and then views user2's profile page, the dispatch getUser(2) action is called right after the page is rendered. Since user1's info is still in the state, it will flash their info for a very short time, and then show the loading spinner until the new user is loaded.

I read about dispatching a resetUser(id) action on every unmount of the page, but I'm not sure if this is the right way to go. Also, one of the features is if a user is viewing their own page, they have an edit button which redirects them to /edit-profile. If I reset the state on every unmount, I'll have to fetch their profile again (in the edit page), even though I just did that when they viewed their page.. And that doesn't seem like it makes sense.

Any ideas how to solve this? Thanks!

like image 784
Ethan Avatar asked Dec 30 '25 11:12

Ethan


1 Answers

The render phase runs after mounting. And you stated that previous data is being shown before new data. It seems that you have asynchronous mounting:

async componentDidMount() {}

It will continue rendering even before mounting phase is completed. To avoid issue, you may use synchronous nature of mounting:

componentDidMount(){}

Where you'll call api data.

Now, when you reach to rendering phase it will have new data available before rendering and won't flash you old data.


You now may be wondering how to call api asynchronously. You can create a asynchronous function and call that function inside the synchronous componentDidMount.

componentDidMount() {
  yourAsyncFunc()
}
async yourAsyncFunc() {} // api call

How can I do this with React hooks?

While using useEffect, don't implement async:

useEffect(async () => 

Implement it simply:

useEffect(() => {
  // you can still use asynchronous function here
  async function callApi() {}
  callApi()
}, []) // [] to run in similar to componentDidMount

If you miss second parameter to useEffect then you are not ensuring it to run on mounting phase. It will run before, after, and in the rendering phase depending on case.

like image 122
Bhojendra Rauniyar Avatar answered Jan 01 '26 03:01

Bhojendra Rauniyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!