useStateXCallback()
This hook is similar to useCallback()
, but will also provide an API for your callbacks to work with StateX state. This hook can be used to construct a callback that has access to the StateX state and the ability to update the StateX state.
Some motivations for using this hook may include:
- Asynchronously read StateX state without subscribing a React component to re-render if the atom or selector is updated.
- Defering expensive lookups to an async action that you don't want to do at render-time.
- Dynamically updating an atom or selector where we may not know at render-time which atom or selector we will want to update.
function useStateXCallback<P extends ReadonlyArray<unknown>, R>(
fn: (props: { set: StateXSetter; get: StateXGetter }, ...args: P) => R,
deps: DependencyList,
): (...args: P) => R;
Example
const callback = useStateXCallback(({ get }, param1, param2) => {
set(atom, 1);
const value = get(atom);
console.log(value + param1 + param2); // 3
}, []);
callback(1, 1);
fn
- The user callback function with access to set & set to read and/or write to global statedeps
- An optional set of dependencies for memoizing the callback. LikeuseCallback()
, the produced callback will not be memoized by default and will produce a new function each time. You can pass an empty array to always return the same function instance. If you pass values in thedeps
array a new function will be used if the reference equality of any dep changes. Those values can then be used from within the body of your callback without getting stale. (SeeuseCallback
)