javascript - 使用 react-hooks 在每个渲染器上创建处理程序的性能损失

标签 javascript reactjs arrow-functions react-hooks

我目前对新 react 的用例感到非常惊讶 hooks API 以及您可以用它做什么。

在实验过程中出现的一个问题是,在使用 useCallback 时,总是创建一个新的处理程序函数只是为了将其丢弃是多么昂贵。

考虑这个例子:

const MyCounter = ({initial}) => {
    const [count, setCount] = useState(initial);

    const increase = useCallback(() => setCount(count => count + 1), [setCount]);
    const decrease = useCallback(() => setCount(count => count > 0 ? count - 1 : 0), [setCount]);

    return (
        <div className="counter">
            <p>The count is {count}.</p>
            <button onClick={decrease} disabled={count === 0}> - </button>
            <button onClick={increase}> + </button>
        </div>
    );
};

虽然我将处理程序包装到 useCallback 中以避免每次渲染时都传递一个新的处理程序,但仍然必须创建内联箭头函数,但在大多数情况下只会被丢弃.

如果我只渲染几个组件,可能没什么大不了的。但是,如果我执行 1000 次,对性能的影响有多大?是否有明显的性能损失?什么是避免它的方法?可能是一个静态处理程序工厂,只有在必须创建新处理程序时才会被调用?

最佳答案

React FAQs 给出解释

Are Hooks slow because of creating functions in render?

No. In modern browsers, the raw performance of closures compared to classes doesn’t differ significantly except in extreme scenarios.

In addition, consider that the design of Hooks is more efficient in a couple ways:

Hooks avoid a lot of the overhead that classes require, like the cost of creating class instances and binding event handlers in the constructor.

Idiomatic code using Hooks doesn’t need the deep component tree nesting that is prevalent in codebases that use higher-order components, render props, and context. With smaller component trees, React has less work to do.

Traditionally, performance concerns around inline functions in React have been related to how passing new callbacks on each render breaks shouldComponentUpdate optimizations in child components. Hooks approach this problem from three sides.

因此,钩子(Hook)提供的整体好处远大于创建新函数的代价

此外,对于功能组件,您可以通过使用 useMemo 进行优化,以便组件在其 props 没有变化时重新渲染。

关于javascript - 使用 react-hooks 在每个渲染器上创建处理程序的性能损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335950/

相关文章:

javascript - react : How to hide a component by clicking on it?

javascript - CSS id 选择器是行不通的

javascript - 在文本输入控件中,如何用退格键替换删除,反之亦然?

javascript - 对象方法(Javascript)内部词法作用域绑定(bind)的机制是什么?

javascript - clearTimeout 行为异常

javascript - 看似相等的字符串的奇怪问题

javascript - 无法获取json数据,给出Cors或回调错误

javascript框架原型(prototype)到jquery

javascript - 箭头函数 "this"绑定(bind)在 React 组件中不起作用

javascript - ES6 类方法在 forEach 循环内不返回任何内容