0

I am working on a React project that was built primarily using React Class Components. Recently, the team decided to begin pivoting to functional components with hooks.

Is there a way for functional and class components to access the same contexts? In other words, if I have a context provider that is set up as a class/consumed by class components, can I then use a down-stream functional component to access and update that context?

The same question goes the other way (setting up provider to use useContext() hook and accessing it through a class component)

I have seen a lot online about "how to use context api," but have yet to see one that combines them instead of simply explaining the two ways to use context.

3
  • You need to watch this: youtube.com/… Commented Feb 19, 2021 at 21:08
  • You can also just change the entire application to functional based components to make the whole process smoother. Commented Feb 20, 2021 at 14:02
  • @Bruno that is the long-term plan, but the size of the project does not allow for an entire overhaul/refactor of the product all at once Commented Feb 22, 2021 at 12:15

1 Answer 1

0

You can still use context in class based components.

Better still, just turn the particular component you're trying to refractor to a function based component.

Doesn't necessarily mean to rewrite the code.. just change things like the the class to const and the name of the component. Next remove the render method and leave only the return. Every other thing like the creating functions can be done above the return and inside the component body like regular functions.

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

Comments

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.