Skip to content

Commit

Permalink
add js version
Browse files Browse the repository at this point in the history
  • Loading branch information
behnammodi committed Jan 23, 2022
1 parent e1c0887 commit e20a0e7
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion text/0000-use-state-ref.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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<T>(initialValue: T): [T, (nextState: T) => void, () => T] {
const [state, setState] = useState(initialValue);
Expand All @@ -51,6 +53,17 @@ function useStateRef<T>(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.
Expand Down

0 comments on commit e20a0e7

Please sign in to comment.