EventEmitter
singleton and using it directly in our components.
```tsx
-import {createContext, useContext, useState, useMemo} from "react";
+import * as React from "react";
import EventEmitter from "eventemitter3";
const emitterSingleton = new EventEmitter();
const Foo = () => {
const [foo, setFoo] = useStatejest
if follow these guidelines:
-- Export the singleton from its own file.
+- Export the singleton from its own file. TODO(kevinb): provide an example of how to
+ mock the singleton.
- If you have a custom class instead of using EventEmitter
be sure to export
that as well so that you can use it when mocking the singleton.
+### State
+
+Using an event emitter means that we're responsible for updating the state. In the
+example above, we've chosen to do that in the Parent
component. We
+could've also sub-classed EventEmitter
and made it responsible for managing
+state. Ideally though, I think we'll probably want to adopt a state management library
+like jotai
, zustand
, or recoil.js
.
+
## Exercise
The code in the exercise/ folder in this lesson is the same as the solution/ folder
diff --git a/src/react-render-perf/lesson-03/exercise/color-picker-event-emitter.ts b/src/react-render-perf/lesson-03/exercise/color-picker-event-emitter.ts
index 4b85bdc..3d3c45c 100644
--- a/src/react-render-perf/lesson-03/exercise/color-picker-event-emitter.ts
+++ b/src/react-render-perf/lesson-03/exercise/color-picker-event-emitter.ts
@@ -11,8 +11,11 @@ export class ColorPickerEventEmitter extends EventEmitter {
return () => this.off(color, callback);
}
- public onSelectedColorChange(callback: (selectedColor: string) => void) {
+ public onSelectedColorChange(
+ callback: (selectedColor: string) => void,
+ ): () => void {
this.on("any", callback);
+ return () => this.off("any", callback);
}
public selectColor(color: string) {
diff --git a/src/react-render-perf/lesson-03/exercise/color-picker.tsx b/src/react-render-perf/lesson-03/exercise/color-picker.tsx
index b498271..3f04768 100644
--- a/src/react-render-perf/lesson-03/exercise/color-picker.tsx
+++ b/src/react-render-perf/lesson-03/exercise/color-picker.tsx
@@ -1,12 +1,14 @@
-import {useContext, useState} from "react";
+import * as React from "react";
import Grid from "./grid";
import {ColorPickerContext} from "./color-picker-context";
export default function ColorPicker() {
- const [color, setColor] = useState+ In this exercise, we want you to remove the context and use the + event emitter directly. +