Chapter 3: Sharing Component State with Context
React has provided Context since version 16.3. Context has nothing to do with states, but it's a mechanism for passing data from component to component instead of using props. By combining Context with a component state, we can provide a global state.
In addition to the Context support provided since React 16.3, React 16.8 introduced the useContext
hook. By using useContext
and useState
(or useReducer
), we can create custom hooks for a global state.
Context is not fully designed for global states. One of the known limitations is that all Context consumers re-render upon updates, which can lead to extra re-renders. It's a general recommendation to split a global state into pieces.
In this chapter, we discuss the general recommendations for using Context and show some concrete examples. We also discuss some techniques to use Context with TypeScript. The goal is to make you feel confident with using Context for a global...