{ 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
- 296