Using React Tracked with useState and useReducer
The primary use case of React Tracked is to replace a use case of React Context. The API in React Tracked is specifically designed for this use case.
We will explore two usages with useState
and useReducer
. First, let's learn about the usage with useState
.
Using React Tracked with useState
Before exploring the usage of React Tracked with useState
, let's revisit how we can create a global state with React Context.
We first create a custom hook, which calls useState
with an initial state value:
const useValue = () => useState({ count: 0, text: "hello" });
Defining the custom hook is good for TypeScript because you can grab the type with the typeof
operator.
The following is a definition of our Context:
const StateContext = createContext< ReturnType<typeof useValue> | null >(null);
It has a type annotation in TypeScript. The default value is null
.
To...