I was reading how to use react hooks, callback
, and memo
adequately. It was mentioned on one of the post that a bad implementation will cost more vs not using useMemo
We started implementing our code to exactly separate the code for UI logic and for the view only
for example, we created a custom hook that handles the UI logic
controller
const useController = () {
const [click, setClick] = useState(0)
const refresh = () => {
setClick(0)
}
const onClick = () => {
setClick(click 1)
}
return {
click, onClick, resfresh
}
}
component
const Component = () => {
const {click, onClick, resfresh} = useController()
return(
<div>
<label onClick={onClick}>{click}</label>
<button onClick={refresh}>refresh</button>
</div>
)
}
My question here is whether the functions inside the hook are as well recreated when the component is re-rendered. If so, should it be ok to wrap a function inside a custom hook with useCallback
or useMemo
if there's an actual need?
CodePudding user response:
Yes, you're creating new handler functions every time Component rerenders - but if the only children of the component are built-in JSX elements, it'll have no noticeable effect at all.
If you wanted to return a stable reference to the functions - which would be a good practice but not necessary - yes, it'd be perfectly fine (and expected) to use useCallback
or useMemo
.
const useController = () {
const [click, setClick] = useState(0);
const refresh = useCallback(() => {
setClick(0);
}, []);
const onClick = useCallback(() => {
setClick(click => click 1);
}, []);
return {
click, onClick, refresh // make sure to spell this right
};
};
Whether useMemo
or useCallback
are used would matter more if you had other React components who were children of the Component component use them.
const Component = () => {
const {click, onClick, resfresh} = useController();
return(
<SomeOtherComponent {...{ click, onClick, refresh }} /> // make sure to spell this right
);
};
Making sure the references are as stable as possible can make thing easier performance-wise (...in unusual situations) and can also make their uses easier, especially in conjunction with the common exhaustive-deps linting rule.