Last active
March 30, 2021 04:46
-
-
Save norami/2a525d54d576922691c8b735d7596fe3 to your computer and use it in GitHub Desktop.
Functional Component with minimum external store with event handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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