Using a module state as a global state in React
As we discussed in Chapter 3, Sharing Component State with Context, React Context is designed to provide different values for different subtrees. Using React Context for a singleton global state is a valid operation, but it doesn't use the full capability of Context.
If what you need is a global state for an entire tree, a module state might fit better. However, to use a module state in a React component, we need to handle re-rendering ourselves.
Let's start with a simple example. Unfortunately, this is a non-working example:
let count = 0; const Component1 = () => { const inc = () => { count += 1; } return ( <div>{count} <button onClick={inc}>+1</button></div> ); };
You will see count
0
at the beginning. Clicking button
increases the count
variable, but it doesn't trigger the component...