DEV Community

Discussion on: Latest React Component Syntax, May 2020

Collapse
 
mubbashir10 profile image
Mubbashir Mustafa • Edited

A quick note: when initializing useState with some value, then it's redundant to add type definition. TS would automatically pick it from the default value.

so, the snippet
const [count, setCount] = React.useState<number>(0);

can be rewritten as:
const [count, setCount] = React.useState(0);

Collapse
 
nosyminotaur profile image
Harsh Pathak

Not always true. If you initialise a value to null, TS then only allows null for the field.
Then we need to do this ->

const [data, setData] = 
useState<number | null>(null);
Collapse
 
mubbashir10 profile image
Mubbashir Mustafa

The comment wasn't for union types. It was an addition to the article from a purely linting perspective. Let's suppose you have a loader and you are using const [loading, setLoading] = useState<boolean>(false), in that case <boolean> is redundant here.

Collapse
 
ngduc profile image
Duc Ng

Right. The example just demonstrated how to put a type in, it will be helpful for custom types.