ย
๐ตโ๐ซ
๐ญ
useMemo === useCallback
memorization
overusing useMemo
solid understanding
figure out best practices
๐
Approve
Simplify
๐ค
// useState returns an array. Index zero is the current value
const ref = useState({ current: initialValue })[0]
# PRESENTING CODE
๐คจ
๐ง
const shallowEquals = (prevDeps, currentDeps) => {
if (!Array.isArray(prevDeps) || !Array.isArray(currentDeps)) {
return false;
}
if (prevDeps.length !== currentDeps.length) {
return false;
}
for(item of prevDeps) {
if (!Object.is(prevDeps[item], currentDeps[item])) {
return false;
}
}
return true;
};
const useMyMemo = (create, dependencies) => {
const val = useRef(create());
const prevDependencies = useRef([]);
if (!shallowEquals(dependencies, prevDependencies.current)) {
val.current = create();
prevDependencies.current = [...dependencies];
}
return val;
};
# PRESENTING CODE
Customise useRef by useState
ย
useMemo similar to useRef
Combine useRef with auto-update functionality
What about useCallBack
useCallback((e) => onClick(id, e.target.value), [onClick, id]);
// is equivalent to
useMemo(() => (e) => onClick(id, e.target.value), [onClick, id]);
๐
# PRESENTING CODE
const ChildComponent = React.memo(({
filterData
}) {
console.log('child rendering ...')
return < > ChildStuff < />
})
const ParentComponent = () => {
const filterData = () => {
// do something
}
const handleClick = useCallback(filterData, [])
return <ChildComponent filterData = {
handleClick
}
/>
}
# PRESENTING CODE
const useSlide = (defaultSlideIndex = 1) => {
const [slideIndex, setSlideIndex] = useState(defaultSlideIndex);
const nextSlide = useCallback(() => {
...
}, [slideIndex]);
const prevSlide = useCallback(() => {
...
}, [slideIndex]);
useEffect(async () => {
const dataSlider = await fetchData();
// maybe fetch from API and then pass data to slideIndex
setSlideIndex(dataSlider.length)
}, [slideIndex])
return { nextSlide, prevSlide, slideIndex };
};
@croftyland