From 3bf1cb4f152701975897850c746e6ee873b53d6e Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 26 Jan 2021 16:52:38 -0600 Subject: [PATCH] Add Set The Type For A useState Hook as a React til --- README.md | 3 ++- react/set-the-type-for-a-usestate-hook.md | 29 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 react/set-the-type-for-a-usestate-hook.md diff --git a/README.md b/README.md index ddf8700..8ad3343 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1026 TILs and counting..._ +_1027 TILs and counting..._ --- @@ -735,6 +735,7 @@ _1026 TILs and counting..._ - [@reach/router Renders To A Div](react/reach-router-renders-to-a-div.md) - [Read Only Input Elements](react/read-only-input-elements.md) - [Rendering Multiple Nodes With Fragments](react/rendering-multiple-nodes-with-fragments.md) +- [Set The Type For A useState Hook](react/set-the-type-for-a-usestate-hook.md) - [Specifying Dependencies Of A useEffect Hook](react/specifying-dependencies-of-a-useeffect-hook.md) - [Spelunking Through Components With Enzyme's Dive](react/spelunking-through-components-with-enzymes-dive.md) - [Sync Your react-router State With Redux](react/sync-your-react-router-state-with-redux.md) diff --git a/react/set-the-type-for-a-usestate-hook.md b/react/set-the-type-for-a-usestate-hook.md new file mode 100644 index 0000000..efa9679 --- /dev/null +++ b/react/set-the-type-for-a-usestate-hook.md @@ -0,0 +1,29 @@ +# Set The Type For A useState Hook + +TypeScript can often infer the type of a `useState` hook. For instance, in the following example, TypeScript infers a type of `boolean`: + +```typescript +const [open, setOpen] = React.useState(false); +``` + +If we have a `useState` hook that can be `null` or a string: + +```typescript +const [error, setError] = React.useState(null); + +setError('There was an error'); +// Argument of type 'string' is not assignable +// to parameter of type 'SetStateAction' +``` + +then we'll get a TypeScript warning when we violate the inferred type of +`SetStateAction`. + +The `useState` can be appropriate typed for this situation like so: + +```typescript +const [error, setError] = + React.useState(null); +``` + +[source](https://www.carlrippon.com/typed-usestate-with-typescript/)