ReactJS Custom Hooks

Tram Ho

ReactJS provides you with a lot of hooks that you can use every day in your project. But besides that you can create your own hooks to use, making code optimization a lot better. Those custom hooks are actually js functions that start with the keyword use and they can call other hooks (built-in or custom).

The need for Custom Hooks: The main reason you should use custom hooks is the DRY (non-repetitive) concept in your react project. For example, you have a logic that uses existing hooks and you need to use that logic in some function. So there will be 2 ways for you to choose

  • Write logic in each component (violating the concept of DRY code)
  • Create a separate function that wraps your logic in it and then import and call it in the components you need to use

The 2nd way will definitely be the better choice for you because you only write the logic once. Here, the function you wrote is called a custom hook. So, whenever you need a logic that can be used in multiple components, think about custom hooks.

Create 1 custom hook: Creating a custom hook is like writing a javascript function whose name starts with use. It can use other hooks inside it, return whatever you want to return, take anything as a parameter. The useCustomHook function in the example below will be a custom hook that uses state counter. The resetCounter increment the counter’s value by 1 and whenever the counter’s value is updated, this function will call the existing use Effect hook. Functions that execute some code (removed to focus on using a custom hook instead of implementing a logic) will be used a lot in components. This custom hook returns a function resetCounter.

Filename- src/useCustomHook.js:

Using custom hooks in components: to use hooks in components just import useCustomHook from useCustomHook.js file in src folder

Filename- src/components/FirstComponent.js:

Filename : src/components/SecondComponent.js:

Filename: src/App.js:

If you open the console in your browser, you’ll see:

If you click the 2nd button, it will happen the same thing as above, check carefully in the console.

Note that both the counters (defined in the custom hook) of the two components are different. The two components use two different states, they don’t share the state. So above, each component will have a variable counter private. Similarly, each component will have its own useEffect and they are executed independently of each other. counter of FirstComponent is updated, the useEffect of FirstComponent will be called, and has no effect on counter of SecondComponent.

In src/components/FirstComponent.js, code similar to below:

Note: it is important to name your custom hook starting with the keyword  use, because without it React cannot recognize it as a custom hook and cannot apply React rules to it.

Bài viết được dịch tại:

Thank you for reading my post

Share the news now