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?
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.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.
How do this two behaviours compose together/interact with each other?
> How do this two behaviours compose together/interact with each other?
What?
1. It’s hard to reuse stateful logic between components
2. Complex components become hard to understand
3. Classes confuse both people and machines
See https://legacy.reactjs.org/docs/hooks-intro.html#motivation for details. Agree or not, but it is a very intentional and well motivated direction.
> Agree or not, but it is a very intentional and well motivated direction.
Agree with problem exists (roughly), disagree on solution.
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. component.use(SubHook, param)
could be used, that would pass the param as a second argument to the constructor.The main reason why this isn't the case, I think, is concurrent mode. Hooks force certain values to be retreived and stay stable during render (i.e. you can only get a component state value during render function) and this is important if there are multiple setup and teardowns going on.
(Concurrent mode is IMO a bit of unfortunate React complexity that a lot of users of React don't really need, and many others can avoid)
function useViewport(initialValue) {
const [state, setState] = useState(initialValue);
useEffect(() => {
return watchViewport((x, y) => setState(x + y))
}, [])
return state.get();
}
// usage
function MyComponent() {
const viewportSize = useViewport()
// use in render
}
I made a couple of assumptions here. From usage, I assume watchViewport is supposed to both subscribe and return a teardown function. I also assume that the viewportState.set/get are functions for getting and setting the tracked value in the component's state.In my opinion, there are many advantages to the hook version and several major disadvantages to the class version:
1. There's no need for hooks to have a value method or React.Components to grow the use or addState methods because the hook is just a function call which returns a value. How it produces that value is up to the code inside the function--which does call out to React--but the fact the function will always be called when MyComponent is called (absent something throwing earlier in the function body of course). The value you see being returned by the hook will always match the value you get when you call useViewport() in your component. These two things are guaranteed to have the exact same behavior as any other JavaScript function call and thus you can reason about the "registration" and value passing without needing to learn any framework-specific APIs.
2. There's no need for an addOnUnmount method on the component object passed to the ViewportHook constructor, because the hook function can use the function component's equivalent to componentWillUnmount (the return value of a useEffect) in the exact same way as a function component can, but without need for external registration.
3. In order to implement the class API, you'd need to either (A) pass the component's actual instance to the hook, or (B) create a new type of value to represent the instance of the component the hook is registering against. Option (B) is yet another API to learn, as you have to learn a new type of object to deal with in a React application. Option (A) would mean figuring out a way to prevent people from calling those methods after construction, OR introducing the possibility of registering a new slice of state partway through. The latter might be possible, and maybe that's even what you intend, but I'd want to know what the expected impact on methods like shouldComponentUpdate or getDerivedStateFromProps would be. Speaking of those...
4. I can't think of any obvious way you could pass previous versions of hook-related instance properties to lifecycle methods in the same way that you can pass prevProps and prevState.
5. Concision: the hook version has a dramatic reduction in the amount of code you have to read
6. Bundle size: because the hook version relies on functions rather than class properties, it can be minified trivially and thus reduce bundle size even more than the obvious reduction in character count would imply
class ViewportHook {
constructor(component) {
this.viewportState = component.addState(this, initialValue)
component.addEffect(() => {
return watchViewport((x, y) => this.viewportState.set({something: x + y})
})
}
value() { return this.viewportState.get() }
}
The hook version is function useViewport() {
const [state, setState] = useState(initialValue);
useEffect(() => {
return watchViewport((x, y) => setState(x + y))
}, [])
return state;
}
I changed the API to be more similar to the existing useEffect where you can return the unsubscribe function. That makes the difference in the size of code non-significant.Again, its more about API design rather than classes or functions.
Another crucial benefit of the class version: you can use hooks in conditions or loops, in any order. This is because they're not called on every render. I also used a unique `key` to pass to `addState`, but its not really a requirement, since the hook constructors only get called once.
I don't understand points 3 and 4, can you elaborate? I'm assuming that when i call `component.use(HookClass)` the component creates a new instance of that hookclass. Regarding learning, I don't think the whole concept of (functional) hooks and their idiosyncracies are any easier to learn than learning one new type of class.
> Bundle size: because the hook version relies on functions rather than class properties, it can be minified trivially and thus reduce bundle size even more than the obvious reduction in character count would imply
I don't think this will make any meaningful difference. The full component methods API (addState, addEffect) is likely to be in use in any nontrivial project, so that can't be minified away. For 3rd party hook classes, they would be small and independend through `use` and easy to minify / dead-code-eliminate if not in use.
Sure! You show ViewportHook's constructor receiving a "component" prop. Since, in the calling component, you call this.use(ViewportHook), the `use` method is supposed to pass some sort of reference of the calling component into ViewportHook's constructor. My question was about what the type of that parameter is. Internally, is `use` something like `use(Hook) { return new Hook(this); }`? If so, you're passing a direct reference to the class instance. I had thought that maybe the framework could pass a more limited delegate for the instance to the constructor to prevent people from doing something silly with it, but that would prevent you from assigning a property safely anyway.
> I don't think this will make any meaningful difference. The full component methods API (addState, addEffect) is likely to be in use in any nontrivial project, so that can't be minified away. For 3rd party hook classes, they would be small and independend through `use` and easy to minify / dead-code-eliminate if not in use.
Object properties can't be safely minified. Any user-defined component using lifecycles will still need to have "constructor", "render", etc in the generated source, whereas identifiers (like "MyComponent" in `const MyComponent = ...`) aren't accessed by being looked up on an object, and thus can safely be minified to one or two character names. This was one of the motivations of the design of hooks. I believe it's called out in the original talk from React Conf 2018.
[Edit]
And regarding point 4: componentDidUpdate receives prevProps and prevState, and shouldComponentUpdate receives nextProps and nextState. How would you provide information about the previous or next version of that hook-based state if it's being tracked as an instance property rather than in the component's state object?
That seems like a good idea. I'll admit my illustration is not a fully fleshed out design, it was meant more to be a sketch of how it would be possible to make a class based design much more capable than the original one was.
> Any user-defined component using lifecycles will still need to have "constructor", "render", etc in the generated source
Ahh I got it - this is not about DCE but about minified names. Not sure why my mind went with dead code elimination.
My first gut feeling is that this wouldn't be as important for everyday users if they already have code splitting / DCE / gzip. I'll look up the video, would be interesting to see some numbers - I'm hoping thats part of the presentation.
> componentDidUpdate receives prevProps and prevState, and shouldComponentUpdate receives nextProps and nextState. How would you provide information about the previous or next version of that hook-based state if it's being tracked as an instance property rather than in the component's state object?
I'm giving up having a single component state with the new API - this class based hook API also allows you to have multiple states. So I'm going to focus on the props part.
In the hook constructor, you would be able to use a listener for componentUpdate:
component.onUpdate((prevProps, props) => { run code });
You could also do something like component.watch(() => [otherHook.someValue(), this.someState.get()], () => {
// callback
})
to get render-time change detection (equivalent to `useEffect(fn, [otherHookValue, someStateValue])`).Its all a bit wordier, no doubt, but I feel that most of the capabilities can be implemented.
I have to go to bed, but if you'd like to see a much better explanation about why hooks were adopted, I highly recommend the [checks notes] 1,401 comment-long discussion[1] on the PR for adopting the hooks RFC back in 2018, as this sort of design was brought up frequently. Especially worthwhile is Sebastian Markbåge's ending summary about why the team was going with hooks[2].
[1] https://github.com/reactjs/rfcs/pull/68 [2] https://github.com/reactjs/rfcs/pull/68#issuecomment-4393148...
(I can't resist commenting I suppose - I did follow that thread as much as time permitted back then, and I couldn't agree with the conclusion from the arguments presented. Specifically, I was unconvinced that dispatch performance and file size were that dramatically different. In my experience, classes are very efficient in modern engines and code-splitting means much more than minification, especially after gzip. Even if they are the right trade-offs for Facebook, its unclear whether they're the right trade-offs for the rest of React users and the community as a whole - from my experience it has errected a bit of a barrier to front end work for backend engineers because there is a steep and weird learning curve at the start)
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.
Only new things now are suspense and server components, both completely optional.
React is amazingly stable and largely backward compatible (where it’s not there are usually codemods available to do most of the work).
Redux, mobx, etc also were all options to fix the basic state management in React.
I concede it is not every week. I should have said the preferred approach changes too often for my taste.
This might be controversial but imo the lack of state management in React is a pro not a con. It means the community can innovate instead of being stuck with whatever the framework provides as is standard with most other frameworks. A lean focussed but flexible API.
You can choose the flavor that works for your, patterns like React Query, SWR, Zustand, the Atom based stuff, it's all a big #win imo. I like having options.
Also I'd say changes in preferences are not exclusive to React. React did make the hook change (while still supporting the old!), but otherwise the preferred approaches are not per se exclusive to React.
I would add that there is nothing wrong with sticking to what you are using atm. You don't have to use the shiny new thing if the old works well!
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 that specifically deals with when using JSX, compared to other templating systems.
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.
To illustrate statefulness: If you drop a flummy ball on the floor, it will bounce back and doesn't change. If you drop an egg, it will change and you can't drop it easily again. The ball is stateless, the egg is stateful.
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.