javascriptreactjsreact-functional-componentreact-class-based-component

React extends for function component?


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.


Solution

  • 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.