diff --git a/src/@lib/hooks/index.ts b/src/@lib/hooks/index.ts index 220d6fe..583576c 100644 --- a/src/@lib/hooks/index.ts +++ b/src/@lib/hooks/index.ts @@ -2,3 +2,4 @@ export * from "./useDeepMemo"; export * from "./useMemo"; export * from "./useCallback"; export * from "./useRef"; +export * from "./useState"; diff --git a/src/@lib/hooks/useRef.ts b/src/@lib/hooks/useRef.ts index 6665f45..559a7a1 100644 --- a/src/@lib/hooks/useRef.ts +++ b/src/@lib/hooks/useRef.ts @@ -2,6 +2,6 @@ import {useState} from "react"; export function useRef(initialValue: T): { current: T } { // React의 useState를 이용해서 만들어보세요. - const [data, setData] = useState({current : initialValue}); + const [data, setData] = useState({current : initialValue}); return data; } diff --git a/src/@lib/hooks/useState.ts b/src/@lib/hooks/useState.ts new file mode 100644 index 0000000..b1fdf27 --- /dev/null +++ b/src/@lib/hooks/useState.ts @@ -0,0 +1,37 @@ +import React from 'react'; + +// 이것저것 수정해서 구현해보려다 실패 +type SetStateAction = T | ((prevState: T) => T); +type Dispatch = (action: SetStateAction) => void; + +const states: unknown[] = []; +let currentStateIndex = 0; + +export function useState(initialValue: T): [T, Dispatch] { + const index = currentStateIndex; + + if (states[index] === undefined) { + states[index] = initialValue; + } + + const setState = (newValue: SetStateAction) => { + const value = typeof newValue === 'function' + ? (newValue as (prevState: T) => T)(states[index] as T) + : newValue; + + if (states[index] !== value) { + states[index] = value; + React.Component.prototype.forceUpdate.call(this); + } + }; + + currentStateIndex++; + + React.useEffect(() => { + return () => { + currentStateIndex = 0; + }; + }); + + return [states[index] as T, setState]; +} \ No newline at end of file diff --git a/src/App.tsx b/src/App.tsx index f74ec47..cff5e3b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,8 +1,6 @@ -import React, {useState, createContext, useContext, useEffect} from "react"; +import React, {useState, createContext, useContext } from "react"; import { generateItems, renderLog } from "./utils"; import {memo, useCallback, useMemo } from "./@lib"; -// import {memo} from "react"; -import {deepEquals} from "./@lib"; // 타입 정의 interface Item { @@ -37,9 +35,9 @@ interface AppContextType { } const AppContext = createContext(undefined); -const ThemeContext = createContext(undefined); -const AuthContext = createContext(undefined); -const NotificationContext = createContext(undefined); +const ThemeContext = createContext(undefined); +const AuthContext = createContext(undefined); +const NotificationContext = createContext(undefined); // 커스텀 훅들 const useTheme = () => {