hooks
internal hooks
useMemo and useCallback
Now I finally get it!
useMemo
is for caching repetitive computing, like memoized
function in render() of Class component.
const Button = React.memo(() => {
console.log("Button Rendered!");
window.alert("Button Rendered");
return <button onClick="">Press me</button>;
});
useCallback
is for passing functional props to children component, in case that everytime the component rerenders there will be a new functional prop so the pureComponent or React.memo of the children component cant work properly.
但是 useMemo 有一定消耗,还是尽量遵循 keep useful state within component 为好
It mentioned that how to extract custom fetch api hook
and reducer hook
further more.
Here's a usecase forreducer hook
. We need to set isError, isLoading or data imperatively:
setError(false);
setLoading(false);
To improve it, we can collect these actions together as fetchSuccess, which returns the new states descriptively:
const dataFetchReducer = (state, action) => {
switch (action.type) {
case 'FETCH_SUCCESS':
return { isError: false, isLoadding: false };
}
};
dispatch(fetchSuccess)