Skip to content

Commit

Permalink
MyReact 컨택스트가 컴포넌트를 한 번 만 렌더한다.
Browse files Browse the repository at this point in the history
  • Loading branch information
jeonghwan-kim committed Apr 9, 2024
1 parent 2b1930c commit c04f11d
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions 2-hook/src/lib/MyReact.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,30 +81,49 @@ const MyReact = (function MyReact() {
cleanups.forEach((cleanup) => typeof cleanup === "function" && cleanup());
}

function createContext(initialValue) {
const emitter = createEventEmitter(initialValue);
function createContext(defaultValue) {
let emitter;

function Provider({ value, children }) {
if (!emitter) {
emitter = createEventEmitter(value);
}

React.useEffect(() => {
emitter.set(value);
}, [value]);

return <>{children}</>;
}

function getValue() {
return emitter ? emitter.get() : defaultValue;
}

function on(handler) {
emitter?.on(handler);
}

function off(handler) {
emitter?.off(handler);
}

return {
Provider,
emitter,
getValue,
on,
off,
};
}

function useContext(context) {
const [value, setValue] = React.useState(context.emitter.get());
const [value, setValue] = React.useState(context.getValue());

React.useEffect(() => {
context.emitter.on(setValue);
context.on(setValue);

return () => {
context.emitter.off(setValue);
context.off(setValue);
};
}, [context]);

Expand Down

0 comments on commit c04f11d

Please sign in to comment.