React Custom Hooks

Narendra Singh Rathore
2 min readOct 25, 2020

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

import React, { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Basic Hooks

Additional Hooks

For detail explanation, please click on the links.

Custom Hook

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. Let’s try to understand by implementation.

Scenario 1: Window resize event

The resize event fires when the document view (window) has been resized. We can listen to event in react.js component(s) itself, but what if we need that same event in multiple components, so in that case we can make custom hook that can be reused.

import { useState, useEffect } from "react";/*** ### Custom react hook: useWindowResize* Return current window innerWidth using custom react hook*/function useWindowResize() {const [size, setSize] = useState(window.innerWidth);useEffect(() => {const cb = () => setSize(window.innerWidth);window.addEventListener("resize", cb);return () => {window.removeEventListener("resize", cb);};}, []);return size;}export { useWindowResize };

Note: We can use predefined hooks in our custom hook.

Now just import in components you need and that’s it, we have created reusable custom hook which tells current inner Width 🎉.

In your component(s)

import React from "react";import { useWindowResize } from "./customHooks";export default function Profile() {const size = useWindowResize();return <div className="container">Profile: {size}</div>;}

Scenario 2: To be continued…

Like👍, follow 🚗.

To know more on best practices in react.js application, please check the my opensource project on GitHub.

https://github.com/narendrasinghrathore/todo-app-react ( star the repository if you like, follow me on GitHub also.)

✨🎉🎁 Keep sharing and stay safe 👩‍🚀

--

--