问题
in this react example from https://reactjs.org/docs/hooks-custom.html, a custom hook is used in 2 different components to fetch online status of a user...
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
};
});
return isOnline;
}
then its used in the 2 functions below:
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
function FriendListItem(props) {
const isOnline = useFriendStatus(props.friend.id);
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>
);
}
my question is, will the function be executed individually everywhere where it is imported into a component? Or is there some thing like sharing the state between components, if it is defined as a separate exported function? e.g I execute the function only once, and the "isOnline" state is the same in all components?
And if its individually fetched, how would I have to do it to fetch data only once globally, and then pass it to different components in my React app?
回答1:
In the case you mention, the function is executed at every component's render. So each component keeps a state value independently from the others. For this specific example it's what I would probably use.
If you need some state data to be shared globally (like authentication status), or between several components at different levels in DOM tree, one option is to use the React context.
First you define a new Context, by using the React.createContext()
function.
Check this link for more info: https://reactjs.org/docs/context.html
Then, you must use the Context.Provider (a component which keep context value and manages the updates) at top of your DOM hierarchy and then you can use the hook useContext()
to refer to context value (provided from the Context provider) in descendant components at any level.
Check this link for that: https://reactjs.org/docs/hooks-reference.html#usecontext
回答2:
Whenever you use a custom hook, there will be separate instances of the hook within your App and they won't share the data unless you are using context API within them which is common across multiple instances or your ChatAPI holds data in one place eg in a singleton class instance or within browserStorage/using API.
useState or useReducers will have separate instances within your App.
You can simply think of this as useState and useEffect being written multiple times within your code app in individual component
来源:https://stackoverflow.com/questions/57602715/react-custom-hooks-fetch-data-globally-and-share-across-components