Skip to content

Commit

Permalink
Merge pull request #190 from lad-tech/121-useLatest
Browse files Browse the repository at this point in the history
docs(api): added docs for useLatest hook
  • Loading branch information
Emilien7 authored Apr 2, 2024
2 parents c08d8d0 + 6162a70 commit a26f010
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
2 changes: 0 additions & 2 deletions docs/docs/API/utils/useLatest.md

This file was deleted.

31 changes: 31 additions & 0 deletions docs/docs/API/utils/useLatest.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
React state hook that returns the latest state as described in the [React hooks FAQ](https://legacy.reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function).

This is mostly useful to get access to the latest value of some props or state inside an asynchronous callback,
instead of that value at the time the callback was created from.

## Example

```tsx
import {useLatest} from "@lad-tech/mobydick-utils";
import {Button, Text, View} from "@lad-tech/mobydick-core";
import {Alert} from "react-native";

const Demo = () => {
const [count, setCount] = React.useState(0);
const latestCount = useLatest(count);

const handleAlertClick = () => {
setTimeout(() => {
Alert.alert(`Latest count value: ${latestCount.current}`);
}, 3000);
}

return (
<View>
<Text>You clicked {count} times</Text>
<Button onPress={() => setCount(count + 1)}>Click me</Button>
<Button onPress={handleAlertClick}>Show alert</Button>
</View>
);
};
```

0 comments on commit a26f010

Please sign in to comment.