React Custom Hooks and Dynamic Loading

kartik goyal
2 min readSep 3, 2023

--

Hook is the normal javascript function. We can build our own hook

Why should we even build hooks?
Reusability
Readibility
Maintability — seperation of concern
Testable — Seperate test cases for utilities
offload functionality
Hook have their own reconcilation process.

Create our own hook — whenever you think you can extract code from component, create a hook thus changes your code to cleaner code.
To create a hook,
1. Extract process logic
2. Reconcilation is working behind the soon for each hook
3. Always remember type of return statement
4. Always create a hook with ‘use’ at the start of the name (such as useOnline) helps react to identify it is a hook. For eg.

useOnline hook — to determine whether the client is online/offline.

There is a event listener which determine whether the client is online/offline using the event we can determine. In network tab under the devtools we have the power to be offline

how many times should I use event listener for below functionality? 1 — useEffect

//user js
const useOnline = () => {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
window.addEventListener(“online”, () => { setIsOnline(false); });
window.addEventListener(“offline”, () => { setIsOnline(true); });
}, []);
return isOnline;
}

Whenever you add event listener you need to clean it up otherwise it will keep holding the event on other pages also.

removing eventlistener need to pass the same function which passed during creating the event in the return statement of useEffect.

Why dynamic loading?

Bundler such as parcel used for bundling — bundling is good but bundling all the component in 1 index file degrade the performance.

Thus, Using
chucking /
code splitting /
dynamic bundling /
lazy loading /
On Demand Loading /
Dynamic Import
improves the performance.
It does create multiple bundle file as required. Require lazy() and Suspense() for achieving this. It dynamically loads the data.

Using lazy function (named import from react)
const Instamart = lazy(() => import())

upon on demand loading -> upon loading -> suspend loading
When you are loading your component in demand where react will try to suspend it because it is a promise.

Using Suspense (named import from react) take care of on demand loading also it have fallback prop for shimmer ui.

Never ever dynamically load a component inside component.

--

--