react batch updates (sometimes :-) )

reactjs will batch multiple state changes made in the same event handler and react waits until all code in the event handler has run before processing state updates.

For example an onClick() handler may run multiple state updates. Instead of re-rendering after each individual state update in the handler, react batches them and renders once; after the handler completes (see example 1 below). This behavior is known as "batching"

But an important thing to realize is: "React will not batch updates if they're triggered outside of a React event handler, like in a setTimeout()"

This means that debounced handler functions will not be able to take advantage of react batching.

But we want debounce and batching both! 😠

Ok, you want it, you got it 😀. Here are some options since react batching won't work:

1. in your handler, change from setting multiple useState setStates to 1 state update, this could be achieved using a useReducer or setting a complex object in a useState

2. depending on your circumstance, your could use useRef to store values that don't need a state update and then have one final state setter which you know triggers the re-render. Option 1 is definitely preferred (option 2 is a bit hacky innit).


example 1 (no debounce): the two state updates in handleOnSearch are batched into one render: 

  const [searchTerm, setSearchTerm] = useState('');

  const [filteredList, setFilteredList] = useState('');

  const handleOnSearch = (searchText) => {

    setSearchTerm(searchText);


    setFilteredList(() => list.filter(item =>

      item.name.toLowerCase().includes(searchText.toLowerCase())

    ));

  };


  return (

  <input change={(e) => handleOnSearch(e.currentTarget.value)} type="text" />

  <p>your search text is {searchTerm}<p>

  );

Comments

Popular posts from this blog

My Reading Lists

angular js protractor e2e cheatsheet

deep dive into Material UI TextField built by mui