Dan Profile picture
Dan
Ex. founder. Frontend developer, perfecting the art of imperfection. Serverless. UI/UX. Going solo #indiemaker.

Aug 29, 2020, 11 tweets

React Hooks are amazing → but if you're not careful, **performance** can spiral out of control.

Here are the fundamentals for optimum performance. #reactjs #javascript #es6

A thread 👇

State, 1/3)

Avoid using multiple setState's for combined data models, especially in async functions as they re-render per setState.

State, 2/3)

Instead, combine into a single setState for simple state logic.

State, 3/3)

Or, useReducer for complex state logic to ensure consistent behaviour.

Memorization, 1/5)

Re-rendering of parents causes children to re-render if they have props (even if those props don't change the dom).

Memorization, 2/5)

Use React.memo to render the component and memoize the result, preventing unnecessary re-renders.

Before the next render, if new props are the same, React reuses the memoized result & skips the next render.

Side note, it's not always applicable or necessary to memorize components.

Check out this image via @panzerdp for heuristics on when to memorize.

@panzerdp Memorization, 3/5)

However, React only performs a shallow comparison for prop changes in memorized components.

Which means, object props & functions props (that don't change) still cause unnecessary re-renders.

@panzerdp Memorization, 4/5)

Do not fear, to prevent unnecessary re-renders:

useMemo → to memorize objects and/or values which require expensive computation.

useCallback → to memorize functions.

@panzerdp Memorization, 5/5)

Finally, use dependencies to ensure that changes are only allowed if one of the dependencies has changed.

Below, I have a function which depends on "value". If value changes, the function updates, which rightly, causes a re-render.

@panzerdp End)

In this thread, we covered useState, useReducer, memo, useMemo & useCallback for better React performance.

For reference, all the code shown in the images can be found here:

jsfiddle.net/ankleio/n0ozv6…

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling