4 ms·
I have some similar gripes. I find Hooks to save a bit of coding overall. I've found my functional components to be about 10-20% smaller than my class component
by mstudio 6y ago
I have some similar gripes. I find Hooks to save a bit of coding overall. I've found my functional components to be about 10-20% smaller than my class components. I'm not 100% convinced it's really worth it, though.
With class components, my state/props are clearly defined within the constructor and/or PropTypes. This makes it easy to understand the overall architecture of a component. Functional components with Hooks don't have the same sort of structure and can be difficult to understand at a glance.
One of my gripes with Hooks is that listening for async state updates requires more code/complexity than w/classes. In a traditional class component, you can add a second, optional argument as a callback which is called when the state has updated:
setState({ myState: 'newValue' }, () => { this.doSomething(); });
With Hooks, that doesn't apply. The useState "set" function doesn't have a similar argument.
setMyState('newState');
Instead, you need to use 'useEffect' with an optional argument:
useEffect(() => { doSomething(); }, [myState]);
This leads to potentially having many "useEffects" scattered throughout the component.
That said, this is just my experience with Hooks after a few months of working with them. It's entirely possible that I just haven't had enough experience with them yet.
- eat_veggies 6y agoHaving a separate useEffect certainly scatters your code, but it helps prevents bugs that cause your states/effects to go out of sync. If you use a callback on setState in order to listen for async state updates like setState({ myState: 'newValue' }, () => { this.doSomething(); }); then a week later, when you add some different code calling setState({ myState: 'newValue' }) somewhere else without remembering to add the callback, your callback won't run! Callbacks kind of break the declarative/reactive model.
- city41 6y agoComponents with lots of hooks in them remind me of spreadsheets. I find myself tracing from one hook dependency array to the next, trying to follow the logic.
- bryik 6y ago> With class components, my state/props are clearly defined within the constructor and/or PropTypes. What do you mean? PropTypes work just as well with functional components as they do with class components.
- schwartzworld 6y agoThat's a misuse of useEffect. it's much simpler to wrap the set function and just call your other function afterward like this: ``` const handleChange = (value) => { setMyState(value); doSomething(); } ```
- mstudio 6y agoThis does not work. setMyState() is asynchronous. doSomething() would run, but not necessarily with the updated value of the state.
- schwartzworld 6y agoThen make the wrapper function async and await setMyState?