Video Tutorial The hooks useMemo & useCallback


One of the problems encountered with components in the form of functions is the impossibility of "saving" a memory because there is no notion of instance within a function. Also, during a change of state the whole code of your function is restarted to create the new rendering and this can be ineffective in certain situations. useMemo will allow to create a value which will be memorized.

const htmlContent = useMemo (function () {
    return Markdown.parse (content)
}, (happy))

We will thus memorize the return of the function according to the dependence specified in the second parameter. If during a new rendering the dependency has not changed, then we will recover the value in memory and we will avoid doing the processing. On the other hand, if the content has changed since the last rendering, the function will be executed again and the new value will be kept in memory. This method can also be used so as not to generate a new callback with each rendering (and thus allow pure components not to be rendered

function MyComponent () {
     // ....
     const handleClick = function () {
            console.log ('hello')
     }
     return 
}

During each rendering of MyComponent, a new callback is created and, even if the logic inside this callback does not change, the identity verification will fail in the pure component and a new rendering will be done.

function MyComponent () {
     // ....
     const handleClick = useMemo (function () {
         return function () {
            console.log ('hello')
         }
     }, ())
     return 
}

Using the hook useMemo we make sure that the callback does not change between renderings and we avoid rendering at pure component level. There is also a second hook which simplifies writing in the context of callback (the logic is the same as for useMemo).

function MyComponent () {
     // ....
     const handleClick = useCallback (function () {
        console.log ('hello')
     }, ())
     return 
}