News for hackers. Stuff that matters.
Re:A guide to useEffect in React by jameslk on Monday March 11, 2019 @02:22AM (#19357068)
React hooks solve a problem most people don't have. Classes worked fine in 99% cases and have the nice benefit of encapsulating any side effects. Hooks make it easy to hide side effects and dependence on state (think global variables) by letting developers hide these things several layers deep in functions that may get called by components. This is a footgun waiting to go off.

If you need to use state or side effects, just use classes. Most of the time all you need is pure components with fewer stateful components above controlling the pure components. Pass down your state and state modifiers through explicit and easy to follow props (or use a state management system if you find yourself prop drilling). If you're using state and side effects everywhere, you're probably not using React correctly.

Re:A guide to useEffect in React by wereHamster on Monday March 11, 2019 @02:47AM (#19357142)
Hooks solve the problem that state in classes is not compositional. If you have a stateful class that manages two or more bits of state, it's a lot of work to move one bit to a different component: if not already you have to make the other component stateful, move code over there, check that all the lifecycle methods are updated etc. With hooks you can copy&paste one or two lines of code to another component and be done.

I agree that the bulk of your application state should be managed centrally. But I often need small bits of state all over the place, not related to the overall app state but for UX purposes. For those cases hooks are much more pleasant to use that writing stateful classes.

Re:A guide to useEffect in React by jameslk on Monday March 11, 2019 @03:05AM (#19357202)
> it's a lot of work

It should be a lot of work. There should be a penalty for this. State makes your code harder to reason about and should be avoided (i.e. contained) as much as possible.

> But I often need small bits of state all over the place

If you need small bits of state all over the place you may need to rethink things or use a state management system.

The spirit of React hooks might be to make things easier for certain edge cases but instead they will be abused by those who don't understand them to make their code harder to understand. Trust me, I've already started running into this with those who decided to cargo cult React hooks.

Re:A guide to useEffect in React by littlecranky67 on Monday March 11, 2019 @03:20AM (#19357249)
While it is true that you should not overuse state, it is almost impossible in real-world applications not to have it. I.e. a single UI toggle that shows/hides some content requires a field on the components state. Putting this in the props or even a state management container like redux would be overkill.
Re:A guide to useEffect in React by jameslk on Monday March 11, 2019 @03:27AM (#19357263)
I have built real world applications with React (consumer, insurance, B2B, I work at Facebook using React currently). I've handled some pretty crazy edge cases. I've never felt I needed something like hooks. The example you gave me sounds just fine for a "smart/dumb" component pattern[0]. If you need something between props and redux, there's plenty of existing options that work fine. React context and the render props pattern come to mind.

0. https://medium.com/@dan_abramov/smart-and-dumb-components-7c... (The author of this blog post pushes hooks now yet the pattern works well in most cases)

Re:A guide to useEffect in React by littlecranky67 on Monday March 11, 2019 @03:37AM (#19357292)
When you use TypeScript with React (and want sound typings per policy so any type erasures/widenings are considered bad practice) Hooks are a big leap forward.

Typing classes was much to verbose, and the type system of TypeScript to this day is not a perfect fit to type class-based components. Hooks solve this problem - probably unintentionaly.

Example: With Hooks you almost never need to explicitly type the type of state of a component, as whatever you pass to useState() will auto-infer the type. While when using class-based Components, you'd have to specify the state type as a generic argument; you'd have to manually specify it when you set a state using this.setState() as partial types were allowed due to reacts auto-merging of the passed argument to the state. And you'd have to use some kind of Partial<State> type when assigning only some values of the state in the property constructor.

Similar issues exist when using the static defaultProps field in TypeScript - the type couldn't be inferred from the generic class argument, as a Partial<Props> type is valid for the defaultProps field. As a result, the defaultProps (as well as the default state property) is cast as the empty object type {} by default if you don't explicitly assign a type - which makes you lose basically all the type information because every object is assignable to {} in TS.

And if you ever tried to strictly type your HOCs or renderProps you know how hard it was, sometimes utilizing the conditional/mapped generic types feature of TS. This is completely gone with Hook.

I could go on telling how stupid it is when you disable nullable types in TS (strict mode) because TS will not let you use any non-nullable prop inside of render() - even if that prop is initialized in the static defaultProps field. You'd have to override the non-null check using TS exclamation point operator. This is also gone with Hooks.

I don't know if they designed the Hooks API with TS in mind or if this is completely accidental, but if you migrate a TS project with strict mode enabled to Hooks, you will see how much implicit type annotations can be dropped, and still retain strict type checks. Big fan of it.

Re:A guide to useEffect in React by williamdclt on Monday March 11, 2019 @04:32AM (#19357476)
if you migrate a TS project with strict mode enabled to Hooks, you will see how much implicit type annotations can be dropped

I think you meant "explicit"

I agree with you. I've not been too bothered by typing state and default props, but higher-order-components are almost impossible to type properly (a good typedef doubles the LOC count).

I don't like that hooks don't abstract away the shared behaviour as well as HOCs (the component is unaware of the HOC while it it aware of the hook), but being explicit isn't a bad thing either and it's definitely worth it if it makes typing a non-problem

Re:A guide to useEffect in React by thatswrong0 on Monday March 11, 2019 @06:36AM (#19357915)
I wouldn’t say components are unaware of HoCs.. they are implicitly based on the props they accept.
Re:A guide to useEffect in React by williamdclt on Monday March 11, 2019 @02:31PM (#19361488)
Of course, but they don't know if the props come from a HOC or another "normal" component. If you're updating the render() of a component, you don't care where the props come from.

It's not that important TBH, the abstraction is pretty thin

Re:A guide to useEffect in React by jameslk on Monday March 11, 2019 @02:41PM (#19361593)
> With Hooks you almost never need to explicitly type the type of state of a component [...] While when using class-based Components, you'd have to specify the state type as a generic argument

You don't need to do this. You can accomplish the same thing with class syntax. Here's an example:

  class MyComponent extends Component<Props> {
    state = {
      inferredNum: 1, // TS will infer this to be a number
      explicitNullableString: null as string | null, // Tell TS this will be either null or a string
    }
    ...
 
> And you'd have to use some kind of Partial<State> type when assigning only some values of the state in the property constructor.

I can't say I've ever run into this problem with TS and React but maybe I'm not understanding what you're saying? Do you have an example?

> Similar issues exist when using the static defaultProps field in TypeScript

Here's what I do:

  defaultProps: Partial<Props> = {...}
That doesn't seem such a big deal?

> And if you ever tried to strictly type your HOCs or renderProps you know how hard it was, sometimes utilizing the conditional/mapped generic types feature of TS. This is completely gone with Hook.

It wasn't hard to me but I can understand why others don't like generics. Hooks have their own learning curve, so you're trading one thing for another.

> You'd have to override the non-null check using TS exclamation point operator.

This has been fixed with TS 3 I believe.

Re:A guide to useEffect in React by ponyous on Monday March 11, 2019 @06:33AM (#19357906)
I'm writing TS components daily, I'm not sure why, but I never encountered any of the issues you mentioned.

I can only agree that typing HOC was hard when I did it the first time.

Re:A guide to useEffect in React by littlecranky67 on Monday March 11, 2019 @06:58AM (#19357994)
Then let me ask you: How do you type .defaultProps? How do you type the "state" property on the class? If you did explicitly repeat the type already specified in the Generic Type Argument: Component<IProps, IState> you would know what I mean with too verbose (you have to repeat a type that could be infered, but due to TS restrictions isn't able to). If you did not repeat the type for those fields, you lost typesafety without noticing it. You can then go ahead and assign { foo: "bar" } to state (or use it in setState) and will not get a compilation error (which you shold as foo is not a known property for your state).

And I sure as hell bet you do not use "strict" compilation in TS, which opens typing issues everywhere.

Re:A guide to useEffect in React by ponyous on Monday March 11, 2019 @07:27AM (#19358119)
We are using strict mode.

If I do `setState({ undefinedStateKey: 123});` it warns me. Just checked. It may be linting not TypeScript. We have IState defined only as Generic Type Argument.

We define defaultProps as static in class. And you are right defaultProps are not being type-checked against Generic Type Argument IProps.

Re:A guide to useEffect in React by littlecranky67 on Monday March 11, 2019 @07:36AM (#19358148)
Well if you are in strict mode, it should break the build with an error, not a warning. This seems to be a linting rule.

But you see the issue with defaultProps and state here. You can basically assign anything to defaultProps or use in setState() even so you were explicit of the props type in the Generic Type Argument.

Re:A guide to useEffect in React by teniutza on Monday March 11, 2019 @06:40AM (#19357933)
Sometimes I need to create the props at a different level/location and not directly on the component. The interface for the (class component) props is then very useful.
Re:A guide to useEffect in React by littlecranky67 on Monday March 11, 2019 @08:26AM (#19358406)
This is no different when using Hooks. You specify the type of props as the type of the first argument in the functional component:

  function MyComponent(props: IMyComponentProps) { ... }
Where the type definition of IMyComponentProps resides doesn't matter, you can import it from anywhere.
Re:A guide to useEffect in React by teniutza on Tuesday March 12, 2019 @05:11AM (#19366453)
I was simply pointing out that explicitly defining an interface is not necessarily a downside.
Re:A guide to useEffect in React by thatswrong0 on Monday March 11, 2019 @06:30AM (#19357894)
I’ve been using React for almost 4 years straight - I couldn’t disagree more. Hooks are incredibly useful in removing things that pollute the component tree like higher order components or components with render props which are hard to visually parse. If you have a common state pattern that multiple components use, there’s no good way to share that pattern without one of the solutions I just mentioned.. and hooks are by far the cleanest way to do that. Avoiding prop drilling is so easy with something like useContext.

And hooks are always called.. there is no “maybe” when using them.

Re:A guide to useEffect in React by cageface on Monday March 11, 2019 @03:07AM (#19357209)
I've had way more random problems from not binding class members correctly than I have with useEffect. Hooks have allowed me to rip out a bunch of JS class boilerplate and my code is cleaner and easier to read as a result.
Re:A guide to useEffect in React by korm on Monday March 11, 2019 @03:21AM (#19357250)
Are you against using Babel and the class properties proposal? Binding members shouldn't have been a problem in your codebase in recent years.
Re:A guide to useEffect in React by cageface on Monday March 11, 2019 @03:29AM (#19357270)
I use Typescript. I'm not interested in adding another processing/parsing tool to the stack I already have. Hooks are a much more elegant solution to state management than classes, IMO, but it will probably take some time for best practices to emerge, just as they did for classes.
Re:A guide to useEffect in React by paperpunk on Monday March 11, 2019 @03:53AM (#19357348)
TypeScript already supports those 'class properties' - and with a few extra features - so you don't need to use Babel for this syntax: you already have it.

I'd still rather use hooks though :)

Re:A guide to useEffect in React by anonytrary on Monday March 11, 2019 @02:36AM (#19357107)
React hooks are just a fancy (perhaps unnecessary) way of getting people to embrace closures, which help you avoid other common footguns when dealing with temporal data. If you understand closures and you know how to use them to "remember environments", then React hooks are little more than tools for concision.
Re:A guide to useEffect in React by boomlinde on Monday March 11, 2019 @06:11AM (#19357818)
Other than e.g. useEffect returning a function that closes around something within, I don't see what hooks have to do with closures.
Re:A guide to useEffect in React by anonytrary on Monday March 11, 2019 @05:37PM (#19363084)
You don't need hooks to do any of this, but hooks have everything to do with closures. Hooks are created every single render, unconditionally, guaranteeing that each hook is one-to-one with the render environment that created it. The point of using hooks is that you are always referencing the props and state at the time of creating the hook and not at the time of running the hook. In this way, hooks become part of your rendered output.
Re:A guide to useEffect in React by boomlinde on Monday March 11, 2019 @10:08PM (#19364743)
I know how hooks work, but what you describe has nothing to do with closures.
Re:A guide to useEffect in React by tanilama on Monday March 11, 2019 @02:50AM (#19357155)
I feel the same way.

And how isn't Hooks are worse off in terms of testability? I have got into too far with it, but it seems to favor small piece of ad-hoc code over classes, which seems neet from the surface, but doesn't feel very encouraging towards tests coverage.

Anyone that applies Hooks to production project can share your experience so far? Would love to see some real world adaptation success stories before making the move.

Re:A guide to useEffect in React by boomlinde on Monday March 11, 2019 @05:31AM (#19357690)
> it seems to favor small piece of ad-hoc code over classes

I think that it's important to realize is that classes aren't the only alternative to small pieces of ad-hoc code. Hooks are composable via functions. If you need to reuse your stateful behavior and side effects you can factor them into functions, and if you don't, you'll have exactly the same problems with classes.

Re:A guide to useEffect in React by girishso on Monday March 11, 2019 @06:33AM (#19357905)
I agree 100%. I think hooks turn pure components into their impure cousins which will eventually make following state changes a nightmare.
Re:A guide to useEffect in React by hazza1 on Monday March 11, 2019 @02:46AM (#19357137)
Hooks solve some problems nicely, the main killer for me is that they don't work with classes, so you end up with 2 wildly different paradigms in your codebase.

Feels like hooks should have been a clean start in a new framework rather than retrofitted into React.

Re:A guide to useEffect in React by boomlinde on Monday March 11, 2019 @06:29AM (#19357891)
I have a hard time grasping this concern. How your codebase ends up depends on how you set it up. The introduction of hooks doesn't magically replace half of your class components with functions using hooks. You can introduce them when and how you want to introduce them.

On the other hand, people who are fine with having state managed both via class components and via hooks (and why shouldn't they be?) can gradually introduce the concept and refactor existing components as needed, if and when they see some advantage in using hooks at all.

If you don't want milk with your coffee, it's not a problem that there's a pitcher of milk at the table.

Re:A guide to useEffect in React by hazza1 on Monday March 11, 2019 @10:40AM (#19359294)
Custom hooks encapsulate logic so you can no longer use it in all of your app
Re:A guide to useEffect in React by _betty_ on Monday March 11, 2019 @01:54PM (#19361104)
This small library [1] let's you use hooks in classes. Probably has some bugs but may be good for a transition period

https://github.com/kesne/with-react-hooks

Re:A guide to useEffect in React by root_axis on Monday March 11, 2019 @08:59AM (#19358595)
IMO React state managers are an anti-pattern; they were somwhat useful before the final context api was introduced, but even back then simply passing down props is almost always the better choice, even when you're passing down multiple levels.
Re:A guide to useEffect in React by revskill on Wednesday March 13, 2019 @02:16AM (#19376188)
With Typescript, it's a non-issue to pass the props down to the tree.
Re:A guide to useEffect in React by ng12 on Monday March 11, 2019 @02:36AM (#19357106)
For me the problem hook solves is the heartache pain I feel when I have to convert a SFC to a React.Component. Adding useState and useEffect feels much more natural. I don't think it's any more or less bug-prone than React.Component, especially because you have to be careful about making sure componentDidMount() and componentDidUpdate() are in sync.
Re:A guide to useEffect in React by snek on Monday March 11, 2019 @02:39AM (#19357117)
but you introduce the danger of relying on an api that determines your state based on the order of function calls. if you accidentally take an api that pretends to work based on call site and use it in a loop or callback everything falls apart.
Re:A guide to useEffect in React by sorahn on Monday March 11, 2019 @04:08AM (#19357397)
It only relies on that order between renders. It’s really a non issue.

I just spend the last month building a new chunk of our app in hooks to try them out, and it’s really nice to be able to wrap up shared stateful logic without HoCs.

A bunch of the HoCs in this app take a “propKey” param, because the HoCs are all stacked on top of each other, and prop collisions happened frequently.

Also, it’s a gigantic pain to use TypeScript and “compose”.

Re:A guide to useEffect in React by williamdclt on Monday March 11, 2019 @04:37AM (#19357493)
it’s really nice to be able to wrap up shared stateful logic without HoCs

agreed. I loved HOCs for the composibility, abused them and very rarely encountered prop collision, but TS (or Flow) made them a massive pain

Re:A guide to useEffect in React by littlecranky67 on Monday March 11, 2019 @04:05AM (#19357386)
Only the order of the hook function calls is tracked. The "danger" of 3rd party APIs is a theoretical one, as in most cases you would not put hook function anywhere else except the first level inside the functional component - not into callbacks or whatnot of 3rd party libraries.
Re:A guide to useEffect in React by tlrobinson on Monday March 11, 2019 @10:34PM (#19364867)
IIRC this is easily preventable using the ESLint rule.
Re:A guide to useEffect in React by arcosdev on Monday March 11, 2019 @06:32AM (#19357904)
They solve the problem of me having to use classes at all.
Re:A guide to useEffect in React by WA on Monday March 11, 2019 @06:37AM (#19357917)
In a way, they are merely syntactical sugar.

I agree with the parent poster. Before, you had functional stateless components. Now you have components that look functional and stateless, but are in fact stateful (and impure).

Re:A guide to useEffect in React by rajangdavis on Monday March 11, 2019 @02:31AM (#19357090)
When do you actually need to use hooks? I saw a nice visual where hooks ended up reducing code, but I am not sure I grok it.
Re:A guide to useEffect in React by jameslk on Monday March 11, 2019 @02:35AM (#19357105)
I've been using React in projects large and small for years and I can remember VERY FEW situations where I said to myself "gee I wish I could bundle a bunch of state or side effects together and share it between components like React mixins of lore". If you can't think of a situation where you need it, that's probably because you don't. Anything plain old JavaScript class components can't handle here were solved by using HOCs/render prop patterns or React context (often in the form of state management libraries such as Redux).
Re:A guide to useEffect in React by sorahn on Tuesday March 12, 2019 @10:23AM (#19368376)
> HOCs/render prop

Both of these inflate the VDOM, and present themselves as a false hierarchy that your app requires. HOCs artificially inflate the props that any component requires, and it's harder to see what props you're actually supposed to pass to the component, vs the ones that should come from a HOC. Hooks remove a lot of these anti-patterns.

Re:A guide to useEffect in React by snek on Monday March 11, 2019 @02:33AM (#19357095)
When you want to work with state in a component (so most of the time) but are too stubborn to admit FP isn't the right choice for the job
Re:A guide to useEffect in React by jameslk on Monday March 11, 2019 @02:41AM (#19357123)
This is my feeling too to be honest. I think hooks are very misguided. Unfortunately it's no longer FP anymore when your "referential transparency" has been completely blown away.
Re:A guide to useEffect in React by jordanwallwork on Monday March 11, 2019 @05:43AM (#19357726)
FP?
Re:A guide to useEffect in React by jameslk on Monday March 11, 2019 @02:45PM (#19361637)
Functional Programming