search
HomeWeb Front-endJS Tutorial[Translation] Refactoring React components using custom hooks
[Translation] Refactoring React components using custom hooksJan 17, 2023 pm 08:13 PM
javascriptfront endreact.js

[Translation] Refactoring React components using custom hooks

I often hear people talk about React function components, mentioning that function components will inevitably become larger and have more complex logic. After all, we wrote the component in "a function", so you have to accept that the component will expand and the function will continue to expand. It is also mentioned in React components:

Since function components can do more and more things, the function components in your code base will overall become longer and longer. [Related recommendations: Redis video tutorial, Programming video]

It also mentioned that we should:

Try to avoid Adding abstractions prematurely

If you use CodeScene, you may notice that it warns you when your functions are too long or complex. If we follow what we said before, we may consider whether we should configure CodeScene related warnings more broadly. Of course this can be done, but I think we should not do this, and we should not refuse to add a lot of abstractions to the code. We can get a lot of benefits from it, and most of the time the cost is not high. We can continue to keep our code health very good!

Dealing with Complexity

We should realize that although the function component is written in "a function", this function can still be like other functions, Can be composed of many other functions. Like useState, useEffect, or other hooks, subcomponents themselves are also functions. Therefore, we can naturally use the same idea to deal with the complexity of function components: By creating a new function, we can encapsulate complex code that conforms to the public pattern.

The more common way to deal with complex components is to decompose it into multiple sub-components. But doing so may feel unnatural or make it difficult to accurately describe these subcomponents. At this time, we can discover new abstract points by sorting out the logic of the component's hook function.

Whenever we see a long list of useState, useEffect or other built-in hook functions in a component, we should consider whether They can be extracted into a custom hook. A custom hook function is a function that can use other hook functions inside it, and creating a custom hook function is also simple.

The component shown below is equivalent to a dashboard, using a list to display the data of a user warehouse (imagine similar to github). This component is not a complex component, but it is a good example of how to apply custom hooks.

function Dashboard() {
  const [repos, setRepos] = useState<Repo[]>([]);
  const [isLoadingRepos, setIsLoadingRepos] = useState(true);
  const [repoError, setRepoError] = useState<string | null>(null);

  useEffect(() => {
    fetchRepos()
      .then((p) => setRepos(p))
      .catch((err) => setRepoError(err))
      .finally(() => setIsLoadingRepos(false));
  }, []);

  return (
    <div className="flex gap-2 mb-8">
      {isLoadingRepos && <Spinner />}
      {repoError && <span>{repoError}</span>}
      {repos.map((r) => (
        <RepoCard key={i.name} item={r} />
      ))}
    </div>
  );
}

We are going to extract the hook logic into a custom hook, we just need to copy this code into a function that starts with use (here we name it useRepos): The reason why

/**
 * 请求所有仓库用户列表的hook函数
 */
export function useRepos() {
  const [repos, setRepos] = useState<Repo[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchRepos()
      .then((p) => setRepos(p))
      .catch((err) => setError(err))
      .finally(() => setIsLoading(false));
  }, []);

  return [repos, isLoading, error] as const;
}

must start with use is that the linter plug-in can detect that what you are currently creating is a hook function instead of an ordinary function. , so that the plug-in can check whether your hook function complies with the correct related rules for custom hooks.

Compared with before refining, the only new things that appeared after refining were return statements and as const. The type hint here is just to ensure that the type inference is correct: an array containing 3 elements, the types are Repo[], boolean, string | null. Of course, you can return anything you wish from the hook function.

Translator's Note: Add as const here. The difference in ts type inference is mainly reflected in the number of numeric elements. Without adding as const, the inferred type is (string | boolean | Repo[] | null)[]. After adding, the type inferred is readonly [Repo[], boolean, string | null].

Apply the custom hook useRepos to our component, and the code becomes:

function Dashboard() {
  const [repos, isLoadingRepos, repoError] = useRepos();

  return (
    <div className="flex gap-2 mb-8">
      {isLoadingRepos && <Spinner />}
      {repoError && <span>{repoError}</span>}
      {repos.map((i) => (
        <RepoCard key={i.name} item={i} />
      ))}
    </div>
  );
}

It can be found that we cannot call anything inside the component now The setter function means that the state cannot be changed. In this component, we no longer need to include the logic to modify the state. These logics are included in the useRepos hook function. Of course if you really need them, you can expose them in the return statement of the hook function.

What are the benefits of doing this? React's documentation mentions:

By extracting custom hook functions, component logic can be reused

We can simply imagine that if other components in this application also need to display the user list in the warehouse, then all this component needs to do is import the useRepos hook function. If the hook is updated, perhaps using some form of caching, or being continuously updated via polling or a more complex approach, then all components that reference this hook will benefit.

Of course, in addition to facilitating reuse, extracting custom hooks also has other benefits. In our example, all useState and useEffect are to achieve the same function - to obtain the library user list. We regard this as an atomic function, then in an It is also common for components to contain many such atomic functions. If we extract the codes of these atomic functions into different custom hook functions, it will be easier to find which states need to be updated synchronously when we modify the code logic, making it less likely to be missed. In addition, the benefits of doing this are:

  • The shorter the function, the easier it is to understand
  • The ability to name atomic functions (such as useRepo)
  • Provide documentation more naturally (the function of each custom hook function is more cohesive and single, and this kind of function is also easy to write comments)

Finally

We have Learn that React's hook function is not that mysterious and can be created just like other functions. We can create our own domain-specific hooks and reuse them throughout the application. You can also find many pre-written general-purpose hooks on various blogs or "hook libraries". These hooks can be easily applied in our projects like useState and useEffect. Dan Abramov's useInterval hook is an example. For example, you have a hook similar to useRepos, but you need to be able to poll for updates? Then you can try using useInterval in your hook.

English original address: https://codescene.com/engineering-blog/refactoring-components-in-react-with-custom-hooks

[Recommended learning :javascript video tutorial

The above is the detailed content of [Translation] Refactoring React components using custom hooks. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
5个常见的JavaScript内存错误5个常见的JavaScript内存错误Aug 25, 2022 am 10:27 AM

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

实战:vscode中开发一个支持vue文件跳转到定义的插件实战:vscode中开发一个支持vue文件跳转到定义的插件Nov 16, 2022 pm 08:43 PM

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

巧用CSS实现各种奇形怪状按钮(附代码)巧用CSS实现各种奇形怪状按钮(附代码)Jul 19, 2022 am 11:28 AM

本篇文章带大家看看怎么使用 CSS 轻松实现高频出现的各类奇形怪状按钮,希望对大家有所帮助!

Node.js 19正式发布,聊聊它的 6 大特性!Node.js 19正式发布,聊聊它的 6 大特性!Nov 16, 2022 pm 08:34 PM

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

浅析Vue3动态组件怎么进行异常处理浅析Vue3动态组件怎么进行异常处理Dec 02, 2022 pm 09:11 PM

Vue3动态组件怎么进行异常处理?下面本篇文章带大家聊聊Vue3 动态组件异常处理的方法,希望对大家有所帮助!

聊聊如何选择一个最好的Node.js Docker镜像?聊聊如何选择一个最好的Node.js Docker镜像?Dec 13, 2022 pm 08:00 PM

选择一个Node​的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

聊聊Node.js中的 GC (垃圾回收)机制聊聊Node.js中的 GC (垃圾回收)机制Nov 29, 2022 pm 08:44 PM

Node.js 是如何做 GC (垃圾回收)的?下面本篇文章就来带大家了解一下。

【6大类】实用的前端处理文件的工具库,快来收藏吧!【6大类】实用的前端处理文件的工具库,快来收藏吧!Jul 15, 2022 pm 02:58 PM

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version