2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.