React Basics - useMemo useCallback Hooks


React Basics: useMemo & useCallback Hooks

useMemo invokes the function then caches result. useCallback caches the function and only runs it if the dependency (included in []) changes (usually a state or props value).

Basic code to implement useMemo and useCallback hooks.


//import this file into App.js
import React, {useState, useCallback} from 'react'
import Count from './Count'
import Button from './Button'
import Title from './Title'

function ParentComponent() {
    const [age, setAge] = useState(25)
    const [salary, setSalary] = useState(50000)

    const incrementAge = useCallback (() => {
        setAge(age + 1)

    const incrementSalary = useCallback(() => {
        setSalary(salary + 1000)
    }, [salary])

    return (
            <Title />
            <Count text="Age" count={age} />
            <Button handleClick={incrementAge}>Increment Age</Button>
            <Count text="Salary" count={salary} />
            <Button handleClick={incrementSalary}>Increment Salary</Button>

export default ParentComponent


import React from 'react'

function Count({text, count}) {
    console.log(`Rendering ${text}`)
    return (
            {text} is {count}

export default React.memo(Count)


import React from 'react'

function Title() {
    console.log('Rendering title component');
    return (

useCallback Hook

</div> ) } export default React.memo(Title)


import React from 'react'

function Button({handleClick, children}) {
    console.log(`Rendering button - ${children}`)
    return (
        <button onClick={handleClick}>

export default React.memo(Button)	

Link your website to this page! Copy and paste the URL below: