useMemo和useCallback的区别

const Child = memo(({data}) =>{
    console.log('child render...', data.name)
    return (
        
child
{data.name}
); }) const Hook =()=>{ console.log('Hook render...') const [count, setCount] = useState(0) const [name, setName] = useState('rose') //不使用useMemo的话,每次创建出来的是一个新的对象 const data = {name} //使用useMemo的话每次对象只创建一次,所以当count改变的时候,Child不会render const data = useMemo(()=>{ return { name } },[name]) return(
{count}
) }
const Child = memo(({data, onChange}) =>{
    console.log('child render...')
    return (
        
child
{data}
); }) const Hook =()=>{ console.log('Hook render...') const [count, setCount] = useState(0) const [name, setName] = useState('rose') const [text, setText] = useState('') //useCallback同理,当count改变时,代码执行到这里时,会再次创建一个新的onChange函数,所以Child组件也会再次render const onChange=(e)=>{ setText(e.target.value) } //使用useCallback后,count改变,Child不会再次render const onChange = useCallback((e)=>{ setText(e.target.value) },[]) return(
count: {count}
text : {text}
) }

你可能感兴趣的:(useMemo和useCallback的区别)