-
Notifications
You must be signed in to change notification settings - Fork 62
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
00a56d8
commit 179da75
Showing
4 changed files
with
43 additions
and
7 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import React from 'react'; | ||
|
||
// 이것저것 수정해서 구현해보려다 실패 | ||
type SetStateAction<T> = T | ((prevState: T) => T); | ||
type Dispatch<T> = (action: SetStateAction<T>) => void; | ||
|
||
const states: unknown[] = []; | ||
let currentStateIndex = 0; | ||
|
||
export function useState<T>(initialValue: T): [T, Dispatch<T>] { | ||
const index = currentStateIndex; | ||
|
||
if (states[index] === undefined) { | ||
states[index] = initialValue; | ||
} | ||
|
||
const setState = (newValue: SetStateAction<T>) => { | ||
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]; | ||
} |
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