简体   繁体   English

如何在 onChange function REACT 中使用 useCallback 挂钩

[英]How to use useCallback hook with onChange function REACT

I have simple React component: How I can improve this component by adding useCallback hook?我有一个简单的 React 组件:如何通过添加 useCallback 钩子来改进这个组件? Is it even a good idea to add useCallback hook in this component?在此组件中添加 useCallback 钩子是个好主意吗? If yes, to which function should I add it.如果是,我应该将它添加到哪个function。

 import styled from "styled-components" import React, { useState } from "react" import { useGetFilteredBooks } from "../../hooks/useGetFilteredBooks" import { useRecoilState } from "recoil" import { Books, PageNumber, SearchText } from "../../recoil/globalState" export const SearchBook = () => { const [text, setText] = useRecoilState(SearchText) const [pageNumber, setPageNumber] = useRecoilState(PageNumber) const [setBooks] = useRecoilState(Books); const { refetch } = useGetFilteredBooks(text, setBooks, setPageNumber); const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => { setText(event.target.value) } const handleOnSubmit = (e: any) => { e.preventDefault(); refetch(); } return ( <> <form onSubmit={handleOnSubmit}> <Input value={text} onChange={handleOnChange} placeholder="Enter the name of the book or author" /> <button type="submit">Show</button> </form> </> ) } const Input = styled.input` padding: 10px 10px; width: 300px; `

It is a good idea to memoize a function in useCallback if you know that you will be going to use those functions as a dependency in other hooks like useEffect or useMemo , in your case, your functions are pretty trivial and you are not using them as deps to other hooks, the computation cost of recreating them on each re-render is negligible hence the usage of useCallback , specifically, here is not needed.在 useCallback 中useCallback是个好主意,如果你知道你将使用这些函数作为其他挂钩(如 useEffect 或 useMemo)的依赖项,在你的情况下,你的函数非常微不足道,你没有将它们用作依赖于其他挂钩,在每次重新渲染时重新创建它们的计算成本可以忽略不计,因此useCallback的使用,特别是在这里不需要。 Just be aware that if you put other non memoized functions in the deps array of a useCallback, that will be worth nothing.请注意,如果您将其他非记忆函数放在 useCallback 的 deps 数组中,那将一文不值。 If you still plan to wrap those functions in useCallback to use them in other components / hooks:如果您仍计划将这些函数包装在useCallback中以在其他组件/挂钩中使用它们:

 import styled from "styled-components" import React, { useState, useCallback } from "react" import { useGetFilteredBooks } from "../../hooks/useGetFilteredBooks" import { useRecoilState } from "recoil" import { Books, PageNumber, SearchText } from "../../recoil/globalState" export const SearchBook = () => { const [text, setText] = useRecoilState(SearchText) const [pageNumber, setPageNumber] = useRecoilState(PageNumber) const [setBooks] = useRecoilState(Books); const { refetch } = useGetFilteredBooks(text, setBooks, setPageNumber); const handleOnChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => { setText(event.target.value) },[]) // No deps needed here according to ESLint, since react setState<s> do not change during re-renders. const handleOnSubmit = useCallback((e: any) => { e.preventDefault(); refetch(); },[refetch]) // refetch is needed here, since it might change during re-renders, you should make sure to memoize that function as well return ( <> <form onSubmit={handleOnSubmit}> <Input value={text} onChange={handleOnChange} placeholder="Enter the name of the book or author" /> <button type="submit">Show</button> </form> </> ) } const Input = styled.input` padding: 10px 10px; width: 300px; `

What does useCallback do? useCallback有什么作用?

Per the docs :根据文档

useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. useCallback 将返回一个记忆版本的回调,只有当其中一个依赖项发生变化时才会发生变化。

So, memoized callbacks are essentially functions that survive rerender cycles.因此,记忆回调本质上是在重新渲染周期中存活下来的函数。

Why would we need memoized callbacks?为什么我们需要记忆回调?

Per the docs :根据文档

This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (eg shouldComponentUpdate).这在将回调传递给依赖于引用相等性的优化子组件以防止不必要的渲染时很有用(例如 shouldComponentUpdate)。

Combining memoized callbacks with components that rely on reference equality, useEffect is an example in functional components, avoids rerendering these child components unnecessarily.将 memoized 回调与依赖引用相等性的组件相结合, useEffect是功能组件中的一个示例,避免了不必要地重新渲染这些子组件。

Are you using components that rely on reference equality?您正在使用依赖于引用相等性的组件吗?

No. To make your application just "work", at the moment you don't need useCallback .不。为了让您的应用程序“正常工作”,目前您不需要useCallback

Should you still apply useCallback for performance?您是否仍应使用useCallback来提高性能?

One might think, useCallback might enable better performance since functions aren't recreated.有人可能会认为, useCallback可能会带来更好的性能,因为不会重新创建函数。 This has been discussed in an article by Kent C. Doods or in this reddit .这已在 Kent C.Doods 或此reddit文章中进行了讨论。 The bottom line is that premature, unscientific optimization is a waste of time, and potentially harmful.归根结底,过早的、不科学的优化是浪费时间,而且可能有害。 Refrain from applying memoization if you're application works and is fast enough.如果您的应用程序可以正常运行并且速度足够快,请不要使用记忆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM