shouldComponentUpdate in function components

前端 未结 3 834
刺人心
刺人心 2020-12-24 04:46

I have a question regarding React\'s shouldComponentUpdate (when not overwritten). I do prefer pure, function components, but I am afraid that it updates every

3条回答
  •  盖世英雄少女心
    2020-12-24 05:36

    Another approach is to use useMemo to update values only when watched ones are updated:

    const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
    

    In case of objects there's an option of using state hook to cache the value of interested variable, after making sure it's updated. Eg by using lodash:

    const [fooCached, setFooCached]: any = useState(null);
    
    if (!_.isEqual(fooCached, foo)) {
      setFooCached(foo);
    }`). 
    
    const showFoo = useMemo(() => {
        return 
    Foo name: { foo.name }
    }, [fooCached]);

提交回复
热议问题