Home > Web Front-end > JS Tutorial > [Translation] Refactoring React components using custom hooks

[Translation] Refactoring React components using custom hooks

青灯夜游
Release: 2023-01-17 20:13:51
forward
1265 people have browsed it

[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>
  );
}
Copy after login

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;
}
Copy after login

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>
  );
}
Copy after login

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template