diff --git a/text/0000-use-state-ref.md b/text/0000-use-state-ref.md index c55c67d4..c37e75f0 100644 --- a/text/0000-use-state-ref.md +++ b/text/0000-use-state-ref.md @@ -24,7 +24,7 @@ useEffect(() => { }, []); ``` -Also, in this example `useCallback` doesn't need a dependency to know `count`'s value, so `useCallback` inside function just performs once. that's awesome +Also, in this example, `useCallback` doesn't need a dependency to know `count`'s value, so `useCallback` inside function just performs once. that's awesome ```js const [count, setCount, getCount] = useStateRef(); @@ -41,6 +41,8 @@ const handleClick = useCallback(() => { # Detailed design A basic of implementation for `useStateRef` that we can use in project is: + +TS version: ```js function useStateRef(initialValue: T): [T, (nextState: T) => void, () => T] { const [state, setState] = useState(initialValue); @@ -51,6 +53,17 @@ function useStateRef(initialValue: T): [T, (nextState: T) => void, () => T] { } ``` +JS version: +```js +function useStateRef(initialValue) { + const [state, setState] = useState(initialValue); + const stateRef = useRef(state); + stateRef.current = state; + const getState = useCallback(() => stateRef.current, []); + return [state, setState, getState]; +} +``` + # Drawbacks This is a new hook, so we don't have any breaking change, also we can implement that by internal React hooks.