useMemo
та
useCallback
?
думка авдиторії
думка авдиторії
memo
думка авдиторії
useMemo
function updateMemo<T>(
nextCreate: () => T,
deps: Array<mixed> | void | null
): T {
const hook = updateWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
const prevState = hook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
const prevDeps: Array<mixed> | null = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
if (shouldDoubleInvokeUserFnsInHooksDEV) {
nextCreate();
}
const nextValue = nextCreate();
hook.memoizedState = [nextValue, nextDeps];
return nextValue;
}
useCallback
function updateCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
const hook = updateWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
const prevState = hook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
const prevDeps: Array<mixed> | null = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
hook.memoizedState = [callback, nextDeps];
return callback;
}
areHookInputsEqual
function areHookInputsEqual(
nextDeps: Array<mixed>,
prevDeps: Array<mixed> | null,
) {
...
for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
if (is(nextDeps[i], prevDeps[i])) {
continue;
}
return false;
}
return true;
}
const a = useValue();
const b = useAnotherValue();
const c = useMemo(() => a + b, [a, b]);
return <MyComponent value={c} />;
const a = useValue();
const b = useAnotherValue();
const c = a + b;
return <MyComponent value={c} />;
const array = [...]
const onClick = useCallback((item, index) => { ... }, []);
const showModal = useCallback(() => { ... }, []);
return (
<>
<Button onClick={showModal}/>
{array.map((item, index) =>(
<MyComponent onClick={() => onClick(item, index)} />
))}
</>
)
const array = [...]
function onItemClick(item, index) { ... };
function showModal() { ... };
return (
<>
<Button onClick={showModal}/>
{array.map((item, index) =>(
<MyComponent onClick={() => onItemClick(item, index)} />
))}
</>
)
Ре-рендер відбудеться в будь-якому випадку, якщо вам компонент не
мемоїзований явно через memo
.
Дякую. Тепер питання. Бігом.
ютуб канал «Сергій Бабіч та Дивовижний світ веб розробки»