Re:Thinking in React Hooks
by ArchReaper on Thursday December 12, 2019 @04:11PM
(#21776521)
Unless I'm missing something, you don't need all that just to have 'componentDidMount' eg:
export const useMounted = (f) => {
useEffect(f, []);
}
Edit: originally: export const useMounted = (f) => {
useEffect(() => {
f();
}, []);
}
Re:Thinking in React Hooks
by atombender on Thursday December 12, 2019 @04:22PM
(#21776628)
Ah, of course. The use of dependency lists in React is something I keep forgetting exist. Thanks.
Functional components force your component lifecycle into a funnel where the lifecycle becomes obvious, because all the inter-dependencies are already there.
For componentDidMount, you can replicate this easily with hooks:
Extracting anything into a hook is trivial: Implementing an unmount callback is also trivial.The useMounted() example, coincidentally, shows a real benefit to hooks: Easy extraction of reusable logic. Hooks are like plugins this way. For example, one hook I've written that I use all the time is this [1], it lets you get a callback every time your component resizes. If you were to do this with a class-based component, you'd have to use an ugly HOC, which results in lots of unnecessary wrapping/nesting.
For componentDidUpdate, useMemo() is arguably easier to deal with.
[1] https://gist.github.com/atombender/b95bbd2014f6a3ec303b843a9...