react use memo code example
Example 1: useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Example 2: react memo
function MyComponent(props) {
}
function areEqual(prevProps, nextProps) {
}
export default React.memo(MyComponent, areEqual);
Example 3: how to use react memo hooks
function moviePropsAreEqual(prevMovie, nextMovie) {
return prevMovie.title === nextMovie.title
&& prevMovie.releaseDate === nextMovie.releaseDate;
}
const MemoizedMovie2 = React.memo(Movie, moviePropsAreEqual);
Example 4: how to use react memo hooks
const computeLetterCount = word => {
let i = 0;
while (i < 1000000000) i++;
return word.length;
};
const letterCount = useMemo(() => computeLetterCount(word), [word]);
Example 5: import React, { memo } from 'react';
const MyComponent = React.memo(function MyComponent(props) {
});