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 0dfb3fe
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions 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,9 @@ 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 +54,18 @@ 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 All @@ -73,4 +88,4 @@ This RFC introduce a new hook, so we have to add some section to React documenta

# Unresolved questions

- do we need to implement a new hook or embed it to `useState`?
- do we need to implement a new hook or embed it to `useState`?

0 comments on commit 0dfb3fe

Please sign in to comment.