React Context - Context.Consumer vs Class.contextType
Asked Answered
M

1

12

I am learning about the somewhat newly introduced React.Context API, but I've noticed some inconsistencies on it's consumption across examples. Some use the original Context.Consumer HOC method, while some (including the React Docs) use the static Class.contextType method.

What's the difference and why the inconsistency?

Magen answered 21/1, 2019 at 4:26 Comment(1)
Documented in Q&A format as I couldn't find a single satisfactory concise search result when googling things question as of today.Magen
M
19

Turns out that the static Class.contextType was newly introduced on React v16.6.0, as the Context.Consumer method proved problematic on class components. Also, there does seem to be one major difference between using both, and it's that the static Class.Context only allows you to subscribe to a single context.

The good news is that both of them seem to reliably listen of Context changes which means if you only have a single Context API, then both are good enough.

Magen answered 21/1, 2019 at 4:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.