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

React hooks I think are 70% cool and 30% anti-pattern.

The problem is that there are subtle bugs that just aren't obvious at first.

Here's a simple one.

let count: number = 0;

const myCallback = React.useCallback(() => { ++count; return count; }, []);

... so if you had a button that read the value of 'count' it would always return zero.

The reason why is that useCallback caches the value of 'count' and you get the stale version each time.

You have to add 'count' in a dependency on useCallback before the last paren.

There are about 2-4 of these that I need to write down and document but this one has bitten me most often.

Also, React, in general, can't work well with Typescript to catch compiler issues.

For example, Typescript can catch compile errors when you're building a component and you're missing a variable name.

With React context it's more of a global and if you are using a component which doesn't have context setup you will/could get a runtime error or at least a bad bug.

It would be MUCH better, IMO, to have a React-like language that was Typescript aware from the beginning.




> You have to add 'count' in a dependency on useCallback before the last paren.

My linter yells at me that there's going to be a bug if I do that, have you looked into your linting settings?


I saw that recently they added this to eslint... you're using eslint or tslint?


Is there any doc about how this caching is implemented ? I still don't understand why we need to feed this dependency array to have an up to date version of the count variable.


Not Typescript, but elm[0] was the React-like language.

[0] https://elm-lang.org/




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

Search: