Micro State Management with React Hooks by Daishi Kato

Micro State Management with React Hooks by Daishi Kato

Author:Daishi Kato
Language: eng
Format: epub
Publisher: Packt Publishing Ltd.
Published: 2022-01-24T00:00:00+00:00


Detecting property access

Can we do render optimization automatically, without using a selector function to explicitly specify which part of a state is to be used in a component? There is something called state usage tracking, which is used to detect property access and use the detected information for render optimization.

For example, let's suppose we have a useTrackedState hook that has the state usage tracking capability:

const Component = () => {

const trackedState = useTrackedState();

return <p>{trackedState.b.c}</p>;

};

This works as trackedState can detect that the .b.c property is accessed, and useTrackedState only triggers re-renders when the .b.c property value is changed. This is automatic render optimization, whereas useSelector is manual render optimization.

For simplicity, the previous code block example is contrived. This example can easily be implemented with useSelector, the manual render optimization. Let's look at another example using two values:

const Component = () => {

const trackedState = useTrackedState();

return (

<>

<p>{trackedState.b.c}</p>

<p>{trackedState.e.g}</p>

</>

);

};

Now, this is surprisingly difficult to implement with a single useSelector hook. If we were to write a selector, it would require memoization or a custom equality function, which are complicated techniques. However, if we use useTrackedState, it works without such complicated techniques.

The implementation of useTrackedState requires Proxy (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) to trap the property access to the state object. If this is implemented properly, it can replace most use cases of useSelector and can do the automatic render optimization. However, there's a subtle case where the automatic render optimization doesn't work perfectly. Let's take a closer look in the next section.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.