by recursive · 3y ago · 0 comments
I've heard this said before, but I don't understand. Could you give an example of component logic that can't be reused under class components?
const { width, height} = useViewport();
return <div>Viewport: {width} {height}</div>
Zooming in, this is just built from a useEffect() to bind event listeners, and and a useState() to hold the current value. Zooming out, it would be easy to write a useBreakpoint() hook that mostly just calls useViewport(). Hooks compose.Before hooks, there weren't great patterns for isolating units of stateful logic from the presentational side of React. A really common pattern was to use "render props" where a component keeps some internal state and passes it into a function-as-child:
<ViewportWatcher>
{({ width, height}) => <div>Viewport: {width} {height}</div>}
</ViewportWatcher>
You'd see these provider-components nested three or four layers deep, and it got ugly. Hooks solved this. class MyComponent {
constructor() {
watchViewPort((x, y) => {
this.something += x + y;
});
}
render() { /* ... */ }
}
watchViewPort(callback) {
addEventListener("resize", (event) => {
// get x and y
callback(x, y);
});
}
This is obviously not production code, and I haven't tried it, so maybe something doesn't work? What is this missing that hooks provide? class MyComponent {
componentWillMount() {
this.stopWatchingViewport = watchViewPort((x, y) => {
this.setState({ something: x + y });
});
}
componentWillUnmount() {
this.stopWatchingViewport();
}
}
watchViewPort(callback) {
const onResize = (event) => {
// get x and y
callback(x, y);
};
addEventListener("resize", onResize);
return () => removeEventListener("resize", onResize);
}
But being able to slice up logic by functionality, rather than by lifecycle event, gets gradually nicer as you have more of it.The hook API could be class based:
class ViewportHook {
// API on use
constructor(component) {
this.viewportState = component.addState(this, initialValue)
const unsubscribe = watchViewport((x, y) => this.viewportState.set({something: x + y}))
component.addOnUnmount(unsubscribe);
// you can also use another hook - hook composition works
this.otherHook = component.use(SubHook);
// use the other hook's api
}
// API to expose (in render)
value() {
return this.viewportState.get()
// use this.otherHook too if you like
}
}
You would be able to use it in a component like this class MyComponent
constructor() {
this.viewport = this.use(ViewportHook);
}
render() {
const viewportSize = this.viewport.value();
// use in render
}
}
Boring, and a bit less weird.I think the obvious OO alternative to hooks would have been this:
class MyComponent {
constructor() {
this.attachBehaviour(new MyBehaviour(this));
this.attachBehaviour(new MyOtherBehaviour(this));
}
render() { /* ... */ }
}
class MyBehaviour implements ComponentLifeCycleHooks {
componentDidMount() { /* ... */ }
componentWillUnmount() { /* ... */ }
componentDidUpdate() { /* ... */ }
}
Weird React didn't even seem to consider when they went to hooks. Would be possible to implement yourself though.I'm not saying this is better than hooks / "composable" / "functional" API (I quite like Vue's composable API) but it's less of a departure from class based components.
Copy/paste gets even worse when you fix the bugs in your code: - use `setState` rather than update a prop - handle remove event listener on dismount
That extra code makes copy/paste even worse, so HOCs become tbe better option. Hooks are even better since they don't require passing callbacks into a component to get the data
> const { width, height} = useViewport();
This could be a library call from a component, using normal language constructs. In some languages it would be a service.
React is great, but I wished they stopped changing things every week.
You've forgotten the teardown logic. If the user navigates from & to this component often. You'll add more and more listeners. over time.
The solution would be to store the teardown logic somewhere in a class field and then call it from a destructor.
Now this unit of logic is in three different places of the class. If you need to integrate multiple units, they interleave and the class becomes convoluted. Also it's easy to forget about the teardown.
Hooks can achieve this lifecycle awareness by default. They aren't the only solution though: Vues' refs and Sveltes' stores achieve similar results.
You can "sort of" reuse component logic with classes, the most common way is by using Higher order components (see https://legacy.reactjs.org/docs/higher-order- components.html).
The example in that article is pretty good: Subscribing to some external data source. That requires on mount, state, and on unmount.
Using HOC's is not actually reusing logic though, it's creating more components and wrapping them to compose the logic. It's a workaround.
HOC's have a bunch of downsides, imo the most obvious one is the props; you need to pass the previous props, and merge in the new ones. That can create conflicts. Another typical one is refs. You need to be very meticulous about structure and how you compose and order your HOC's to make sure it all works.
In hooks you can define this stateful logic truly disconnected from a component, resolving a lot of the issues of HOC's as you can just call a bunch of functions without impacting the render tree. The "plumbing" is much simpler.
Hope that is sort of clear, but let me know if I should clarify any of this.
For instance, I'm not sure what's meant by needing to merge props. I was under the impression that you could pass a subset of properties as an argument to setState, and all else would remain untouched.
I wasn't thinking of using HOC's. I've done a bit of react, but never touched them. I'm just thinking of reusing logic using the same techniques I use to reuse logic in code. React famously asserts "it's just javascript". Javascript provides a way of reusing logic, namely functions. If I have two class components that have the same logic in them, I'm imagining just putting that code in a function. This is not a sophisticated argument. There might be some reason that wouldn't work, but I don't know what it is.
I think this might be quite common, if you haven’t experienced HOC hell I can understand the confusion why hooks are necessary.
In terms of putting it in a function: there is only one state object per component, you could pass setState around, but you can imagine what would happen if many functions call it. It’s also a lot more effort on the implementation as you would have to basically pass state, and call do some sort of update in the lifecycle methods. It would probably work for one function, but with many it will get problematic. You would almost have to write your own pseudo hooks framework to make this work in a decent way.
I think that specifically deals with when using JSX, compared to other templating systems.
Render props (aka. "function as children") are much more free form than HOCs - they allow you to "compose the props" at the site of usage, as opposed to the component implementation.
I don't think there is a use case that HOC covers that cannot be done with render props - please correct me if I'm wrong.
They are imo not ideal as they are hard to memoize because of the render function. It’s funny that if you try to memoize renderprop components you likely have to use some sort of inputs array just like hooks.
Besides the memoization issue it also gets pretty messy if you need to implement many of them. Instead of just putting things in variables you are now nesting many levels deep.
I think renderprops and hooks are functionally not that different, but hooks have better ergonomics when using many.
One of the simplest examples is "useToggle" which just sets a state variable to true or false. Not hard to write in a class component but it's still stuff that you may end up writing a lot.
A lot of similar ones are click and event handlers that need to be cleaned up after the component is unmounted.
useIsMounted is one I use a lot too to ensure I'm not trying to write state on an API callback once a component is unmounted.
You could add each of these to a class with an hoc and end up with withToggle(withIsMounted(withUseMediaEvent(MyComponent))) but that tends to be a bit of a mess.