1

I have a class component that extends another class component:

export default class MyLittleComponent extends TheBigBoy

Now I need to refactor MyLittleComponent to functional component so it works with hooks etc. But then I lose everything inherited from TheBigBoy.

Is there a way to write function component AND to keep the dependency/extension of TheBigBoy?

TheBigBoy is used all over the app so I can't remove it just yet.

I can possibly make a function copy of TheBigBoy and then somehow attach it to MyLittleComponent but what would be the best way as there's no "extends" for function components as far as I know? A hook of some sort? I want to avoid HOC as that's one of the things I'm running away from.

Wordpressor
  • 7,173
  • 23
  • 69
  • 108

1 Answers1

1

In general, React team recommends composition over inheritance.

What you can do though, is to use a two-pronged approach:

  1. Move the logic and state management from TheBigBoy to a custom hook. Then your MyLittleComponent can use that hook.
  2. Turn TheBigBoy into a component that takes children. You can then pass your MyLittleComponent into TheBigBoy

Hope that helps.

Kabece
  • 26
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Albert Einstein Jun 27 '23 at 14:06