Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11팀 이동아] [Chapter 1-3] React, Beyond the Basics #8

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/assignment/src/@lib/context/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/* eslint-disable react-refresh/only-export-components */

export * from "./notification-context";
export * from "./theme-context";
export * from "./user-context";
export * from "./useContextHook";
38 changes: 38 additions & 0 deletions packages/assignment/src/@lib/context/notification-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { createContext, PropsWithChildren, useState } from "react";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

일주일 동안 고민하면서 작성하신게 보이네요ㅠㅠ 고생하셨습니다
작성하신 코드 잘 보고갑니다!!!


interface Notification {
id: number;
message: string;
type: "info" | "success" | "warning" | "error";
}

export interface NotificationContextType {
notifications: Notification[];
addNotification: (message: string, type: Notification["type"]) => void;
removeNotification: (id: number) => void;
}

export const NotificationContext = createContext<NotificationContextType | null>(null);

export const NotificationProvider: React.FC<PropsWithChildren> = ({ children }) => {
const [notifications, setNotifications] = useState<Notification[]>([]);

const addNotification = (message: string, type: Notification["type"]) => {
const newNotification: Notification = {
id: Date.now(),
message,
type,
};
setNotifications((prev) => [...prev, newNotification]);
};

const removeNotification = (id: number) => {
setNotifications((prev) => prev.filter((notification) => notification.id !== id));
};

return (
<NotificationContext.Provider value={{ notifications, addNotification, removeNotification }}>
{children}
</NotificationContext.Provider>
);
};
17 changes: 17 additions & 0 deletions packages/assignment/src/@lib/context/theme-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { createContext, PropsWithChildren, useState } from "react";

export interface ThemeContextType {
theme: "light" | "dark";
toggleTheme: () => void;
}

export const ThemeContext = createContext<ThemeContextType | null>(null);

export const ThemeProvider: React.FC<PropsWithChildren> = ({ children }) => {
const [theme, setTheme] = useState<ThemeContextType["theme"]>("light");
const toggleTheme = () => {
setTheme((state) => (state === "light" ? "dark" : "light"));
};

return <ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>;
};
15 changes: 15 additions & 0 deletions packages/assignment/src/@lib/context/useContextHook.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useContext } from "react";

interface UseContextHookProps<T> {
context: React.Context<T | null>;
name: string;
}

// context선언 후 null 체크
export const useContextHook = <T,>({ context, name }: UseContextHookProps<T>) => {
const result = useContext(context);
if (result === null) {
throw new Error(`use${name} must be used within a ${name}Provider`);
}
return result;
};
43 changes: 43 additions & 0 deletions packages/assignment/src/@lib/context/user-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { createContext, PropsWithChildren, useState } from "react";
import { useContextHook } from "./useContextHook";
import { NotificationContext } from "./notification-context";
import { useMemo } from "../hooks";

export interface UserType {
id: number;
name: string;
email: string;
}

export interface UserContextType {
user: UserType | null;
login: (email: string, password: string) => void;
logout: () => void;
}

export const UserContext = createContext<UserContextType | null>(null);

export const UserProvider: React.FC<PropsWithChildren> = ({ children }) => {
const [user, setUser] = useState<UserContextType["user"] | null>(null);
const { addNotification } = useContextHook({
context: NotificationContext,
name: "Notification",
});

const login = (email: string) => {
setUser({ id: 1, name: "홍길동", email });
addNotification("성공적으로 로그인되었습니다", "success");
};

const logout = () => {
setUser(null);
addNotification("로그아웃되었습니다", "info");
};

const userContextMemo = useMemo(() => {
return { user, login, logout };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user]);

return <UserContext.Provider value={userContextMemo}>{children}</UserContext.Provider>;
};
36 changes: 35 additions & 1 deletion packages/assignment/src/@lib/equalities/deepEquals.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,38 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function deepEquals(objA: any, objB: any): boolean {
return objA === objB;
if (objA === objB) {
return true;
}

if (objA == null || objB == null) {
return false;
}

if (typeof objA !== "object" || typeof objB !== "object") {
return objA === objB;
}

// 유사배열 유무 비교
if (Array.isArray(objA) !== Array.isArray(objB)) {
return false;
}

const keysA = Object.keys(objA);
const keysB = Object.keys(objB);

if (keysA.length !== keysB.length) {
return false;
}

for (const key of keysA) {
if (!keysB.includes(key)) {
return false;
}

if (!deepEquals(objA[key], objB[key])) {
return false;
}
}

return true;
}
34 changes: 33 additions & 1 deletion packages/assignment/src/@lib/equalities/shallowEquals.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,36 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function shallowEquals(objA: any, objB: any): boolean {
return objA === objB;
if (objA === objB) {
return true;
}
if (objA === null || objB === null) {
return false;
}

if (typeof objA !== "object" || typeof objB !== "object") {
return objA === objB;
}

// 유사배열 유무 비교
if (Array.isArray(objA) !== Array.isArray(objB)) {
return false;
}

const keysA = Object.keys(objA);
const keysB = Object.keys(objB);

if (keysA.length !== keysB.length) {
return false;
}

for (const key of keysA) {
if (!keysB.includes(key)) {
return false;
}
if (objA[key] !== objB[key]) {
return false;
}
}

return true;
}
9 changes: 0 additions & 9 deletions packages/assignment/src/@lib/hocs/deepMemo.ts

This file was deleted.

6 changes: 6 additions & 0 deletions packages/assignment/src/@lib/hocs/deepMemo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { deepEquals } from "../equalities";
import { ComponentType, memo } from "react";

export function deepMemo<P extends object>(Component: ComponentType<P>) {
return memo(Component, deepEquals);
}
12 changes: 0 additions & 12 deletions packages/assignment/src/@lib/hocs/memo.ts

This file was deleted.

20 changes: 20 additions & 0 deletions packages/assignment/src/@lib/hocs/memo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ComponentType, createElement } from "react";
import { shallowEquals } from "../equalities";
import { useMemo, useRef } from "../hooks";

export function memo<P extends object>(Component: ComponentType<P>, equals = shallowEquals) {
return (props: P) => {
const oldProps = useRef<P | null>(null);

if (!equals(props, oldProps.current)) {
oldProps.current = props;
}

const MemoizedComponent = useMemo(() => {
return createElement(Component, oldProps.current);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [oldProps.current]);

return MemoizedComponent;
};
}
12 changes: 8 additions & 4 deletions packages/assignment/src/@lib/hooks/useCallback.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { DependencyList } from "react";
import { useMemo } from "./useMemo";

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any
export function useCallback<T extends (...args: any[]) => any>(factory: T, deps: DependencyList): T {
// 직접 작성한 useMemo를 통해서 만들어보세요.
return ((...args) => factory(...args)) as T
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useCallback<T extends (...args: any[]) => any>(
factory: T,
deps: DependencyList
): T {
// eslint-disable-next-line react-hooks/exhaustive-deps
return useMemo(() => factory, deps);
}
3 changes: 2 additions & 1 deletion packages/assignment/src/@lib/hooks/useDeepMemo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ import { deepEquals } from "../equalities";

export function useDeepMemo<T>(factory: () => T, deps: DependencyList): T {
// 직접 작성한 useMemo를 참고해서 만들어보세요.
return useMemo(factory, deps, deepEquals)
// eslint-disable-next-line react-hooks/exhaustive-deps
return useMemo(factory, deps, deepEquals);
}
18 changes: 15 additions & 3 deletions packages/assignment/src/@lib/hooks/useMemo.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
import { DependencyList } from "react";
import { useRef } from "./useRef";
import { shallowEquals } from "../equalities";

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function useMemo<T>(factory: () => T, deps: DependencyList, equals = shallowEquals): T {
// 직접 작성한 useRef를 통해서 만들어보세요.
return factory();
const oldDeps = useRef<Readonly<DependencyList>>(deps);
const memoized = useRef<T | null>(null);

if (memoized.current === null) {
memoized.current = factory();
}

if (memoized.current !== null && !equals(deps, oldDeps.current)) {
memoized.current = factory();
}

oldDeps.current = deps;

return memoized.current;
}
7 changes: 5 additions & 2 deletions packages/assignment/src/@lib/hooks/useRef.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { useState } from "react";

export function useRef<T>(initialValue: T): { current: T } {
// React의 useState를 이용해서 만들어보세요.
return { current: initialValue };
const [ref] = useState<{ current: T }>({ current: initialValue });

return ref;
}
Loading