2

After using class components for some years, I embraced fully the new way of writing functional components and hooks. Instead of the deprecated componentWillReceiveProps where we compare a lot of props and write impossible to understand logic, we can write simple useEffects. Then I got into the issues related to unnecessary inline function declarations that occurred on re-render. This is the place where useCallback methods come. However, for a single component that is not trivial, a lot of segregated methods appeared, and this seem to me more difficult to follow than the old class way.

A short example:

const MyFuncComp = ({ prop1, prop2... }) => {

  // must use useCallback otherwise onClickHandler etc. are computed at every render, when a prop changes

  const onClickHandler1 = useCallback(() => { ... }, [dep1]};
  ...
  const onChangeHandlerN = useCallback(() => ... };

  /*** MANY useCallback /*

  useEffect(() => {... }, [prop1]);

  useEffect(() => {... }, [prop1, prop2]);
  ...
  /*** MANY useEffect
  >>>> this code doesn't look like JavaScript */

  return <div>
    <button onClick={onClickHandler1} />
    <button onClick={onClickHandler2} />
    ...
    <select onChange={onChangeHandler1}>...</select>
    ...

  </div>;
}

Is there any way to better organise the code that I'm not aware?

Paul Pacurar
  • 145
  • 12
  • I think this question is too abstract. If you show an example maybe people will be able to make suggestions on how to reduce/combine some of those hooks. – Christian Fritz Oct 27 '21 at 20:13
  • updated with a short example; I might have a complex codebase which includes subscribing to websockets, but still, I think is not very usual to have such constructs – Paul Pacurar Oct 27 '21 at 20:37
  • I'm skeptical that having a separate onClick/onChange handler for every control is necessary and can't speak to the useEffect usage because we can't see what you're actually doing with it. – ray Oct 27 '21 at 20:47
  • I really don't understand your points. I find it very common to attach events on most of elements that need so (I'm not talking about the
  • s of and
      here). I gave just a partial example of code, but are you saying it is not common to have LOTS of useEffect in functional components? I don't think is reasonable that my question is closed without having an answer, even if my code is wrong
  • – Paul Pacurar Oct 27 '21 at 21:03
  • 1
    @paul I work on complex React apps every day and never need more than a couple useEffect or useCallback hooks in a component. If you’ve got more than that you should reconsider your approach to whatever it is you’re attempting to do. – ray Oct 30 '21 at 02:51