Hooks are the new trend in React Community and are inevitable for any React developer who prefers functional components to the class base components. Hooks changes the way our React code is written, making our code clean and more readable. In this article, we will learn what is custom hooks? how to create React custom hooks? and how to use this hook in our application?

Hooks

They are typical javascript functions used in functional components and allow us to use state and life cycle methods like componentDidUpdatecomponentDidMount, and more in functional components. It plays a major role in code reusability as it allows us to reuse component and state logic across different components.

Custom hooks:

These are normal javascript functions which contain other hooks inside of it alongside with some common stateful logic that can be reused within multiple components. These functions usually begin with the word use.

Before the arrival of custom hooks, were able to handle repeated and redundant stateful logic inside multiple components by relying on Render props and Higher Order Components. But with the custom hooks, we can accomplish this in a much simpler and cleaner way.

Rules of Hooks

They are two rules to follow when using hooks. Fortunately, react provide a linter plugin to enforce these rules automatically:

Rule 1:

Do not call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Rule 2:

Only Call Hooks from React Functions

Don’t call Hooks from regular JavaScript functions. Instead, you can:

  • Call Hooks from React function components.
  • Call Hooks from custom Hooks.

By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.

Now that we are conversant with these rules, let’s build our custom react hook

#react #tutorials #custom react hooks

Building and using custom React hooks in our application
1.45 GEEK