Skip to content

Commit

Permalink
lesson 2: minor content updates
Browse files Browse the repository at this point in the history
  • Loading branch information
beaesguerra committed Jun 18, 2024
1 parent d5f17d9 commit 9bc6f38
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
13 changes: 7 additions & 6 deletions src/react-render-perf/lesson-02/content.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ descendents to be re-rendered. If the number of descendents is large, this can
result in poor rendering performance.

In order to avoid re-rendering all of the descendents we'd like only those
components using the context to re-render. Ideally, the should only re-render
components using the context to re-render. Ideally, they should only re-render
if the data that they're making use of changes.

In the following example, everytime we update the `value` in the context, we
re-render both child components of the context even though only one of them
needs to be update.
needs to be updated.

```tsx filename="index.tsx"
import {createContext, useContext, useState} from "react";
Expand All @@ -34,7 +34,7 @@ const Bar = () => {
const Parent = () => {
const [value, setValue] = useState<FooBar>({foo: 0, bar: 0});
const incrementFoo = () => setValue(fb => {...fb, foo: fb.foo + 1});
const incrementBar = () => setValue(fb => {...fb, foo: fb.foo + 1});
const incrementBar = () => setValue(fb => {...fb, bar: fb.bar + 1});
<>
<FooBarContext.Provider value={value}>
<Foo/>
Expand Down Expand Up @@ -92,7 +92,7 @@ const Parent = () => {
}

<>
<FooBarContext.Provider value={value}>
<FooBarContext.Provider value={emitter}>
<Foo/>
<Bar/>
</FooBarContext.Provider>
Expand All @@ -110,22 +110,23 @@ props so this is trivial to do.

```tsx
import {createContext, useContext, useState, memo} from "react";
import arePropsEqual from "react-fast-compare";

const Foo = memo(() => {
const emitter = useContext(FooBarContext);
const [foo, setFoo] = useState<number>(0);
emitter?.on("foo", setFoo);

return <h1>foo = {foo}</h1>;
});
}, arePropsEqual);

const Bar = memo(() => {
const emitter = useContext(FooBarContext);
const [bar, setBar] = useState<number>(0);
emitter?.on("bar", setBar);

return <h1>bar = {bar}</h1>;
});
}, arePropsEqual);
```

## Exercise
Expand Down
2 changes: 1 addition & 1 deletion src/react-render-perf/lesson-02/exercise/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {ColorPicker} from "./color-picker";
export default function Exercise2() {
return (
<div>
<h1>Solution 2: Prevent Context From Rendering</h1>
<h1>Exercise 2: Prevent Context From Rendering</h1>
<ColorPicker />
</div>
);
Expand Down

0 comments on commit 9bc6f38

Please sign in to comment.