Hacker News new | past | comments | ask | show | jobs | submit login

Hooks are a big deal if you use TypeScript with React. Explicitly typing the state is gone (it will be inferred by what you pass as initial value to useState()). So is weird Partial<TState> typings when setting the initial class state in the constructor or via this.setState().

And if you ever had to deal with correctly typing HOCs or render props you had to dig very deep into conditional/mapped types in TS. With hooks this is basically gone.




With classes you also don't have type state when using 'state = { ... }'.

I think hooks might be nice for data fetching when it comes to TS as it will super easy to get typing.

I'm still not convinced by hooks though.


Yes you do, you have to give the type of the state in the 'extends' clause: 'class MyComponent extends React.Component<TProps, TState> { ... }'. If you omit TState, an empty object {} is assumed for state. And you have to specify the type when updating the state via .setState(), because setState() auto-patches/merges the state. So its fine to pass a Partial<TState> to setState.

With Hooks, the auto-patching goes away, so your call to setMyCustomState() always requires an argument of type TState.

There are similar issues if you use the 'static defaultProps = { ... }' on a class - you have to manually specify the type of defaultProps - often it is Partial<TProps>




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: