Day-14 React with Me

·

2 min read

Custom Hooks and Lazy Loading in React

Custom hooks and lazy loading helps developers create efficient, reusable, and optimized components.

Custom Hooks in React Custom hooks are a mechanism in React to reuse stateful logic across different components. They allow you to extract component logic into reusable functions, promoting code modularity and reducing duplication.

Why Use Custom Hooks?
  • Reusability: Encapsulate and reuse logic across multiple components.

  • Readability: Improve code readability by separating logic from UI.

  • Maintainability: Simplify component code, making it easier to maintain and test.

Benefits of Custom Hooks
  • Cleaner Code: Logic is abstracted away from the component.

  • Focused Components: Components focus on rendering UI.

  • Easy Testing: Test hooks separately from components.

In our app I created a custom hook for showing online/offline according to our network connectivity.

const useOnlineStatus = ()=>{
    const [onlineStatus,setOnlineStatus] = useState("true")
    useEffect(()=>{
        window.addEventListener("offline",()=>{
            setOnlineStatus(false)
        })
        window.addEventListener("online",()=>{
            setOnlineStatus(true)
        })
    },[])
    return onlineStatus

}
export default useOnlineStatus

Lazy Loading in React

Lazy loading is a design pattern that delays the loading of non-essential resources at the initial load time. In React, lazy loading components helps improve the performance of your application by reducing the initial bundle size. We will be using this in our app once our app becomes a large scale application.

Why Use Lazy Loading?
  1. Performance: Improve load time by splitting code into manageable chunks.

  2. Resource Management: Load components only when they are needed.

Benefits of Lazy Loading
  1. Optimized Load Time: Load only what is necessary for the initial view.

  2. Improved User Experience: Faster initial load and smoother transitions.

  3. Efficient Resource Utilization: Load components on demand.

for reference- https://react.dev/learn/reusing-logic-with-custom-hooks

https://react.dev/reference/react/lazy