1/*
2 A common use case is to access a child imperatively:
3*/
4
5function TextInputWithFocusButton() {
6 const inputEl = useRef(null);
7 const onButtonClick = () => {
8 // `current` points to the mounted text input element
9 inputEl.current.focus();
10 };
11 return (
12 <>
13 <input ref={inputEl} type="text" />
14 <button onClick={onButtonClick}>Focus the input</button>
15 </>
16 );
17}
1
2const [a,setA]=useState(0);
3const [b,setB]=useState(0);
4
5const pow=(a)=>{
6 return Math.pow(a,2);
7}
8
9var val= useMemo(()=>{
10 return pow(a); // calling pow function using useMemo hook
11},[a]); // only will be called once a will changed (for "a" we can maintain state)
12
13
14return(
15
16 <input type="text" onChange={(e)=>{setA(e.target.value)}}>
17 <input type="text" onChange={(e)=>{setB(e.target.value)}}>
18
19
20
21 {val} // to access the value from useMemo
22)
23
24
25
26
1const memoizedResult = useMemo(() => {
2 return expensiveFunction(propA, propB);
3}, [propA, propB]);
1const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
2
3Returns a memoized value.
4
5Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.
6
7Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.
8
9If no array is provided, a new value will be computed on every render.
10
11You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.
1/*
2Pass a “create” function and an array of dependencies.
3useMemo will only recompute the memoized value when one
4of the dependencies has changed. This optimization helps
5to avoid expensive calculations on every render.
6*/
7const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);