This is the third post in the series on React Hooks, previously we discussed useContext. I am going to try to keep this as short as possible so here we go:
– Context is used to avoid prop-drilling
– Should only store actual global state like website theme, if the cart is open on an e-commence site.
– Accept a context object and returns context value for that context.
– A component calling useContext will always re-render when the context value changes.
– Context can be optimized using memoization
– useContext only lets you read the context and subscribe to its change
Before we had useContext we used render props to access the context values, the useContext hook allows use to use a context value without using render props. See example below:
While this doesn’t seem to bad it starts getting crazy when you have to consume multiple contexts. Each context means wrapping in another context consumer that will expose the values with a render prop as you have more and more of this things start to snowball:
This is where useContext shines:
If you are looking for a more detailed example you can find one here.
I hope you enjoyed this third post in the react hooks series, this week we discussed useContext. We have now covered the basic hooks, useState, useEffect and useContext. Join me next week when I will be discussing [tba]