Skip to content

Commit 17c5932

Browse files
committed
Enable TypeScript switcher for usePrevious and useWindowSize
1 parent 74b5fbe commit 17c5932

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

src/pages/usePrevious.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ title: usePrevious
44
date: "2018-11-07"
55
gist: https://gist.github.com/gragland/1ed713a68c770ea414c3b92ccf2bdd2f
66
sandbox: https://codesandbox.io/s/pwnl6v7z6m
7+
isMultilingual: true
78
---
89

910
One question that comes up a lot is _"When using hooks how do I get the previous value of props or state?"_. With React class components you have the componentDidUpdate method which receives previous props and state as arguments or you can update an instance variable (this.previous = value) and reference it later to get the previous value. So how can we do this inside a functional component that doesn't have lifecycle methods or an instance to store values on? Hooks to the rescue! We can create a custom hook that uses the useRef hook internally for storing the previous value. See the recipe below with inline comments. You can also find this example in the official [React Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state).

src/pages/useWindowSize.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ title: useWindowSize
44
date: "2018-10-31"
55
gist: https://gist.github.com/gragland/4e3d9b1c934a18dc76f585350f97e321
66
sandbox: https://codesandbox.io/s/jj61r2w6z5
7+
isMultilingual: true
78
---
89

910
A really common need is to get the current size of the browser window.
@@ -57,13 +58,13 @@ function useWindowSize() {
5758
}
5859
```
5960

60-
```typescript jsx
61+
```typescript
6162
import { useState, useEffect } from "react";
6263

6364
// Define general type for useWindowSize hook, which includes width and height
6465
interface Size {
65-
width: number | undefined,
66-
height: number | undefined,
66+
width: number | undefined;
67+
height: number | undefined;
6768
}
6869

6970
// Usage
@@ -108,4 +109,4 @@ function useWindowSize(): Size {
108109

109110
return windowSize;
110111
}
111-
```
112+
```

0 commit comments

Comments
 (0)