useStore Hook
The useStore hook provides the mechanism for components to
“listen” to changes in a store and react to them by re-rendering.
Usage
A basic example of using the useStore hook:
import React, {useState} from 'react';
import MyStore from '../stores/MyStore';
import useStore from '../stores/useStore';
function myComponent(props) {
const [value, setValue] = useState(MyStore.getValue());
MyComponent.getStateFromStores = () => {
const newValue = MyStore.getValue();
if (newValue !== value) {
setValue(newValue);
}
};
useStore([MyStore], MyComponent, 'my-component');
}
Items to note:
-
The
getStateFromStorescomponent is added to the functional component with an explicit assignment. -
The hook receives an array of stores, so a component can listed to more than
one store if needed. All stores, when emitting a change, will call the same
getStateFromStores()callback function, though. - The hook gets a globally unique identifier as the third parameter. This identifier makes sure that the listener will be properly updated with every render and will be properly removed when the component is unmounted.
