0 votes
in React Hooks by
What are common use cases for the useMemo?

1 Answer

0 votes
by
The primary purpose of useMemo hook is "performance optimization".

It returns a memoized value,

It accepts two arguments - create function (which should return a value to be memoized) and dependency array. It will recompute the memoized value only when one of the dependencies has changed.

Using useMemo you achieve:

referential equality of the values (to further send them to props of the components to potentially avoid re-renders)

eliminate redoing of the computationally expensive operations for same parameters

For example:

function App() {

    const [data, setData] = useState([....]);

    function format() {

        console.log('formatting....'); // this will print only when data has changed

        const formattedData = [];

        data.forEach(item => {

            const newItem = //...do soemthing here,

            if (newItem) {

                formattedData.push(newItem);

            }

        })

        return formattedData;

    }

    const formattedData = useMemo(format, [data])

    return (

        <>

        {formattedData.map(item => (

            <div key={item.id}>

            {item.title}

            </div>

        ))}

        </>

    )  

}

Related questions

0 votes
asked Nov 16, 2022 in Jenkins by Robin
0 votes
asked Apr 28, 2022 in Azure Cosmos DB by sharadyadav1986
...