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.

ParentComponent.js

//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)
    },[age])

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

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

export default ParentComponent


Count.js

import React from 'react'

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

export default React.memo(Count)



Title.js

import React from 'react'

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

useCallback Hook

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


Button.js

import React from 'react'

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

export default React.memo(Button)	




 
Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/react/react-basics-usememo-usecallback-hooks/