Skip to content

Instantly share code, notes, and snippets.

@norami
Last active March 30, 2021 04:46
Show Gist options
  • Save norami/2a525d54d576922691c8b735d7596fe3 to your computer and use it in GitHub Desktop.
Save norami/2a525d54d576922691c8b735d7596fe3 to your computer and use it in GitHub Desktop.
Functional Component with minimum external store with event handling
import { EventEmitter } from "events";
import * as React from "react";
import { createContext, useContext, useState } from "react";
const useEmitter = <T extends EventEmitter>(emitter: T) => {
const [_updateCounter, setUpdateCounter] = useState(() => {
let counter = 0;
emitter.on("change", () => {
setUpdateCounter(++counter);
});
return counter;
});
};
const sampleContext = createContext({ emitter: new EventEmitter(), i: 0 });
export const FunctionalComponent = () => {
const context = useContext(sampleContext);
useEmitter(context.emitter);
return (
<div>
{context.i}
<button
onClick={() => {
context.i = context.i + 1;
context.emitter.emit("change");
}}
>
click
</button>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment