Skip to content

Commit

Permalink
add an example
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinbarabash committed Feb 26, 2024
1 parent c550674 commit 6d98572
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions src/react-render-perf/lesson-04/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,77 @@ the children will re-render.
Additionally, we can memoize some or all of the new child components if we want to
prevent them from re-rendering in response props changes.

## Example

Consider `LargeComponent` below. Clicking on either of the buttons will cause
the whole component to re-render.

```tsx
import {useState} from "react";

const LargeComponent = () => {
const [foo, setFoo] = useState<number>(0);
const [bar, setBar] = useState<number>(0);

const foo = <>
<h1>foo = {foo}</h1>
<button onClick={incrementFoo}>increment foo</button>
</>;

const bar = <>
<h1>bar = {bar}</h1>
<button onClick={incrementBar}>increment bar</button>
</>;

return <>
<h1>LargeComponent</h1>
{foo}
{bar}
</>
}
```

Extracting components `Foo` and `Bar` allows those components to update and
re-render indepedently of each other.


```tsx
import {useState} from "react";

const Foo = () => {
const [foo, setFoo] = useState<number>(0);

const foo = <>
<h1>foo = {foo}</h1>
<button onClick={incrementFoo}>increment foo</button>
</>;
}

const Bar = () => {
const [bar, setBar] = useState<number>(0);

const bar = <>
<h1>bar = {bar}</h1>
<button onClick={incrementBar}>increment bar</button>
</>;
}

const ParentComponent = () => {
return <>
<h1>ParentComponent</h1>
<Foo />
<Bar />
</Foo>
}
```

## Notes

- If there are still other things left in the `ParentComponent` that could
trigger a re-render, you may want to memoize some or all of the children components.
- Splitting up components has the added benefit of making the components easier
to test. You can even mock the child components when testing the parent component.

## Exercise

1. Use the profiler in React dev tools to measure the render performance of the code
Expand Down

0 comments on commit 6d98572

Please sign in to comment.