Skip to content

Commit 3f875c0

Browse files
authored
updates for hooks
1 parent 36b24a0 commit 3f875c0

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

README.md

+32
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,31 @@ const [user, setUser] = useState<IUser | null>(null);
212212
setUser(newUser);
213213
```
214214

215+
**useRef**
216+
217+
When using `useRef`, you have two options when creating a ref container that does not have an initial value:
218+
219+
```ts
220+
const ref1 = useRef<HTMLElement>(null)
221+
const ref2 = useRef<HTMLElement | null>(null)
222+
```
223+
224+
The first option will make `ref1.current` read-only, and is intended to be passed in to built-in `ref` attributes that React will manage (because React handles setting the `current` value for you).
225+
226+
The second option will make `ref2.current` mutable, and is intended for "instance variables" that you manage yourself.
227+
228+
**useEffect**
229+
230+
When using `useEffect`, take care not to return anything other than a function or `undefined`, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:
231+
232+
```ts
233+
function DelayedEffect(props: { timerMs: number }) {
234+
// bad! setTimeout implicitly returns a number because the arrow function body isn't wrapped in curly braces
235+
useEffect(() => setTimeout(() => {/* do stuff */}, props.timerMs), [timerMs])
236+
return null
237+
}
238+
```
239+
215240
**Custom Hooks**
216241

217242
If you are returning an array in your Custom Hook, you will want to avoid type inference as Typescript will infer a union type (when you actually want different types in each position of the array). Instead, assert or define the function return types:
@@ -230,6 +255,13 @@ export function useLoading() {
230255
}
231256
```
232257

258+
A helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:
259+
```ts
260+
function tuplify<T extends any[]>(...elements: T) { return elements }
261+
262+
const myTuple = tuplify(false, 1, 'a') // type is [boolean, number, string]
263+
```
264+
233265
If you are writing a React Hooks library, don't forget that you should also expose your types for users to use.
234266

235267
Example React Hooks + TypeScript Libraries:

0 commit comments

Comments
 (0)