r/reactjs • • Jun 26 '21

Resource TIL: state updates aren't always batched together - only in event handlers

/r/learnreactjs/comments/o8grqg/til_state_updates_arent_always_batched_together/
70 Upvotes

15 comments sorted by

56

u/brainless_badger Jun 26 '21

Now that you know that you can start forgetting it because it's getting changed in React 18.

-14

u/0xnoob Jun 26 '21

In the last link - which is from 2018 - Dan Abramov says that this will potentially be changed in React 17 - which was release in 2020.

also: *something something* Suspense *cough* ;)

2

u/brainless_badger Jun 27 '21

Yes this is what they said back then, but they just made an intermediate version before introducing Suspense for data fetching (the 17). So automatic batching and Suspense were both moved to 18.

Not sure why people downvoted you so much.

1

u/0xnoob Jun 27 '21

Wasn't aware of that, thanks for the info!

Not sure why people downvoted you so much.

Yeah... my comment wasn't meant to be taken super serious (thus the smiley), but the reddit community has a harsh voting culture. ¯_(ツ)_/¯

19

u/acemarke Jun 26 '21

Yep. I'd suggest reading my extensive post A (Mostly) Complete Guide to React Rendering Behavior, which covers this topic.

Also, note that React 18 will batch all renders together, always, even outside of event handlers.

2

u/0xnoob Jun 27 '21

Yep. I'd suggest reading my extensive post A (Mostly) Complete Guide to React Rendering Behavior, which covers this topic.

I think I have that one bookmarked in my "reading list"-folder since you published it, but it is so long... but in hindsight, considering how long it took me to figure this behavior out on my own, reading it would have probably saved time. :*(

Also, note that React 18 will batch all renders together, always, even outside of event handlers.

thanks for the link, that's exactly the up-to-date article on that topic I was looking for!

10

u/karlshea Jun 26 '21

Places like this is where useReducer() can be helpful, because you can update both values in one go.

4

u/[deleted] Jun 26 '21

Cool, can you link or write a short example? Interested in how that works.

3

u/hibernatingpanda Jun 27 '21
function reducer(state, action) {
  switch(action.type) {
    case 'PENDING':
      return { ...state, status: 'loading' };
    case 'FULFILLED':
      return { ...state, status: 'success', data: action.data };
    case 'FAILED':
      return { ....state, status: 'failed' };
    default:
      return { ...state };
  }
}

const initState = { status: 'idle', data: null };

function Demo({ url }) {
  const [{ status, data }, dispatch] = useReducer(reducer, initState);

  useEffect(() => {
    async function getData() {
      dispatch({ type: 'PENDING' });

      try {
        const data = await fetch(url);
        dispatch({ type: 'FULFILLED', data };
      } catch(error) {
        dispatch({ type: 'FAILED' });
      }
    }

    if (url) {
      getData();
    }
  }, [url]);

  return (...);
}

Something like that

0

u/[deleted] Jun 27 '21

[deleted]

2

u/hibernatingpanda Jun 27 '21

To each their own but I don't see the need for an extra library to do this. In addition if it is likely that there are other state members I would just stick to useReducer.

1

u/killersquirel11 Jun 27 '21

The prevState param can also be useful

Note Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

const [state, setState] = useState({});  
setState(prevState => {
// Object.assign would also work
  return  {...prevState, ...updatedValues};
});

Another option is useReducer, which is more suited for managing state objects that contain multiple sub-values.

6

u/nameteynamename Jun 26 '21

I think a pattern that helps avoid things like this is grouping associated state together, so you would have some kind of response state with data and status as members. You're already setting their state at the same time here. So you could make sure they "batch" that way. I know you're using this as an example to show the actual batching behavior of react but I thought I'd throw that out there.

1

u/0xnoob Jun 26 '21

Hey,

I hope it's okay to crosspost it here, /r/learnreactjs is sadly not very populated anymore.

Not sure if Resource or Discussion would be the right tag.

1

u/eggtart_prince Jun 27 '21 edited Jun 27 '21

Edit - I'm lost for words.