javascriptreactjsreact-hooks

React with Hooks: When do re-renders happen?


When will a React component using hooks re-render?

Let's assume the component:

Will a re-render happen directly after the following events, and only at those points in time?

Related Question

Let's assume the component has several useState expressions and a user interaction causes multiple states to update.

Will the component re-render multiple times, once per state value that changed, or will it batch these related changes into one single re-render?


Solution

  • A component will re-render in the following cases considering it doesn't implement shouldComponentUpdate for class component, or is using React.memo for function

    Let's assume the component has several useState expressions and a user interaction causes multiple states to update.

    Will the component re-render multiple times, once per state value that changed, or will it batch these related changes into one single re-render?

    useState doesn't merge the updated values with previous ones but performs batching like setState and hence if multiple state updates are done together, one render take place.

    As a side note, react re-render will recreate the functions as well as the return value. For optimization and to cache a function definition between re-renders - useCallback hook.