Logo

dev-resources.site

for different kinds of informations.

React Concepts: Hook Proximity

Published at
6/3/2024
Categories
reactconcepts
react
javascript
hooks
Author
clschnei
Author
8 person written this
clschnei
open
React Concepts: Hook Proximity

Why Hook Proximity?

Prop drilling occurs when you pass data through many layers of components. This leads to complex and difficult-to-maintain code. By maintaining hook proximity, you can localize any side effects, and reduce the need to pass props through the component tree.

As a practical example, we'll create a simple application where two child components need to fetch data from different endpoints. We'll define a simple useFetch abstraction and demonstrate the different patterns.

const useFetch = (url) => {
  const [data, setData] = useState(null);

  async function fetchData() {
    const response = await fetch(url);
    const data = await response.json();
    setData(data);
  }

  return [data, fetchData];
};
Enter fullscreen mode Exit fullscreen mode

Without Hook Proximity

import React, { useState, useEffect } from 'react';
import { useFetch } from './fetch';

export function ParentComponent() {
  const [data1, fetchData1] = useFetch('https://api.example.com/data1');
  const [data2, fetchData2] = useFetch('https://api.example.com/data2');

  return (
    <>
      <ChildComponent1 data={data1} fetchData={fetchData1} />
      <ChildComponent2 data={data2} fetchData={fetchData2} />
    </>
  );
};

function ChildComponent1({ data, fetchData }) {
  return (
    <div>
      <button onClick={fetchData}>Fetch Data 1</button>
      {data && <div>{JSON.stringify(data)}</div>}
    </div>
  );
}

function ChildComponent2({ data, fetchData }) {
  return (
    <div>
      <button onClick={fetchData}>Fetch Data 2</button>
      {data && <div>{JSON.stringify(data)}</div>}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

With Hook Proximity

import React, { useState, useEffect } from 'react';
import { useFetch } from './fetch';

export function ParentComponent() {
  return (
    <>
      <ChildComponent1 />
      <ChildComponent2 />
    </>
  );
};

function ChildComponent1() {
  const [data, fetchData] = useFetch('https://api.example.com/data1');

  return (
    <div>
      <button onClick={fetchData}>Fetch Data 1</button>
      {data && <div>{JSON.stringify(data)}</div>}
    </div>
  );
};

function ChildComponent2() {
  const [data, fetchData] = useFetch('https://api.example.com/data2');

  return (
    <div>
      <button onClick={fetchData}>Fetch Data 2</button>
      {data && <div>{JSON.stringify(data)}</div>}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Explanation

In the first example, the ParentComponent manages the data fetching for both ChildComponent1 and ChildComponent2, and the child components rely on props to trigger the data fetch and receive the data. This approach requires prop drilling, making the code harder to manage as the number of components grows.

In the second example, we use hook proximity by moving the useFetch hook directly into the child components. This eliminates the need for prop drilling, simplifies the component hierarchy, and makes the side effects more localized and easier to reason about.

Conclusion

Avoiding prop drilling by using hook proximity helps create more maintainable and understandable React components. By keeping state and side effects close to where they are needed, you can reduce complexity and improve the clarity of your code.

hooks Article's
30 articles in total
Favicon
Hooks Behind The Scenes 3, UseRef!!!
Favicon
A Complete Guide to All React Hooks for Beginners
Favicon
Using useReducer for Complex State Logic
Favicon
Descobrindo o useCallback do React
Favicon
Discovering React’s useCallback
Favicon
Mastering Code Quality in Laravel: Pint with Git Hooks and Docker
Favicon
React: leveraging custom hooks to extract reusable logic
Favicon
Hooks Behind The Scenes 2, useState!!
Favicon
Mastering React Functional Components: Hooks, useEffect, and Lifecycle Explained
Favicon
JSHooks API compare to CHooks
Favicon
The Ultimate Guide to Wall Hanging Hooks and Display Systems for Your Home and Office
Favicon
How to Detect if an Element is in View with React
Favicon
React useQuery : A Complete Guide
Favicon
{useState} HooK { Briefly Explained};
Favicon
React HooK= { Briefly Explained};
Favicon
What is useState?
Favicon
Actions - React 19
Favicon
React controlled and uncontrolled hooks
Favicon
React Concepts: Hook Proximity
Favicon
Demystifying React's useState Hook: A Comprehensive Guide
Favicon
Mastering React Hooks: Best Practices for Efficient and Maintainable Code
Favicon
Designing React Hooks for Flexibility
Favicon
Unleashing the Power of React Custom Hooks
Favicon
Understanding Context Hooks in React: A Beginner's Guide
Favicon
3 Ways To Create Engaging React Loading Screens with Hooks
Favicon
Understanding the useInteractionTimer Hook: Measuring Component Interaction Time in React
Favicon
Cats Fatc's Quick project
Favicon
All About Custom Hooks: Supercharge Your React Components
Favicon
Suggestion for new syntax of React reducers + context
Favicon
How To Define Typescript onChange Event In React

Featured ones: