{ Don't Forget React Memo }
Previously onย
React Conf
But before we start ...
ย
Understand that thisย is not the near future
๐ตโ๐ซ
๐ญ
useMemo === useCallback
memorization
overusing useMemo
solid understanding
figure out best practices
๐๐ป
Khrystyna Landvytovych
FE engineer, SoftServe
๐
Approve
Simplify
Customise your useMemo
1. ย plain JavaScript object
2. value can be accessed, modified
3. should be persist
Our first steps
๐ค
// useState returns an array. Index zero is the current value
const ref = useState({ current: initialValue })[0]
# PRESENTING CODE
useRef?
๐คจ
Recompute the memoized value only when one of the dependencies has changed
Shallow Compare
๐ง
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
1
Customise useRef by useState
2
ย
useMemo similar to useRef
3
Combine useRef with auto-update functionality
4
What about useCallBack
useCallback((e) => onClick(id, e.target.value), [onClick, id]);
// is equivalent to
useMemo(() => (e) => onClick(id, e.target.value), [onClick, id]);
Bonus part
๐
# 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 };
};
Stay with ๐บ๐ฆ
@croftyland
Code
By Khrystyna Landvytovych
Code
- 253