Exploring global states
React provides primitive hooks such as useState
for states that are defined in a component and consumed within the component tree. These are often called local states.
The following example uses a local state:
const Component = () => {
const [state, setState] = useState();
return (
<div>
{JSON.stringify(state)}
<Child state={state} setState={setState} />
</div>
);
};
const Child = ({ state, setState }) => {
const setFoo = () => setState(
(prev) => ({ ...prev, foo: 'foo' })
);
return (
<div>
{JSON.stringify(state)}
<button onClick={setFoo}>Set Foo</button>
</div>
);
};
On the other hand, a global state is a state that is consumed in multiple components, often far apart in an app. A global state doesn't have to be a singleton, and we may call a global state a shared state instead, to clarify that it's not a singleton.
The following code snippet provides an example of what a React component would look like with a global state:
const Component1 = () => {
const [state, setState] = useGlobalState();
return (
<div>
{JSON.stringify(state)}
</div>
);
};
const Component2 = () => {
const [state, setState] = useGlobalState();
return (
<div>
{JSON.stringify(state)}
</div>
);
};
As we haven't yet defined useGlobalState
, it won't work. In this case, we want Component1
and Component2
to have the same state.
Implementing global states in React is not a trivial task. This is mostly because React is based on the component model. In the component model, locality is important, meaning a component should be isolated and should be reusable.
Notes about the Component Model
A component is a reusable piece of a unit, like a function. If you define a component, it can be used many times. This is only possible if a component definition is self-contained. If a component depends on something outside, it may not be reusable because its behavior can be inconsistent. Technically, a component itself should not depend on a global state.
React doesn't provide a direct solution for a global state, and it seems up to the developers and the community. Many solutions have been proposed, and each has its pros and cons. The goal of this book is to show typical solutions and discuss these pros and cons, which we will do in the following chapters:
- Chapter 3, Sharing Component State with Context
- Chapter 4, Sharing Module State with Subscription
- Chapter 5, Sharing Component State with Context and Subscription
In this section, we learned what a global state with React hooks would look like. Coming up, we will learn some basics of useState
to prepare the discussion in the following chapters.