brunosduarte / github-blog

1 stars 0 forks source link

React Design Patterns #3

Open brunosduarte opened 1 month ago

brunosduarte commented 1 month ago

It is important to emphasize that these patterns not only focus on solving technical problems, but also prioritize code efficiency, readability and maintainability. By adopting standardized practices and well-defined concepts, development teams can collaborate more effectively and build robust and adaptable React applications for the long term.

Why use patterns in React?

The use of design patterns in React is critical to developers because of their ability to reduce development time and costs, mitigate the accumulation of technical debt, ease code maintenance, and promote continuous and sustainable development over time. These patterns provide a consistent structure that streamlines the development process and improves overall software quality.

Custom Hook Pattern

The Custom Hook pattern in React is a technique that allows encapsulating the logic of a component in a reusable function. Custom Hooks are JavaScript functions that use the Hooks provided by React (such as useState, useEffect, useContext, etc.) and can be shared between components to effectively encapsulate and reuse logic.

When to use it

When you need to share logic between React components without resorting to code duplication. To abstract the complex logic of a component and keep it more readable and easier to maintain. When you need to modularize the logic of a component to facilitate its unit testing. When not to use it

When the logic is specific to a single component and will not be reused elsewhere. When the logic is simple and does not justify the creation of a Custom Hook. Advantages

Promotes code reuse by encapsulating common logic in separate functions. Facilitates code composition and readability by separating logic from the component. Improves testability by enabling more specific and focused unit tests on the logic encapsulated in Custom Hooks. Disadvantages

May result in additional complexity if abused and many Custom Hooks are created. Requires a solid understanding of React and Hooks concepts for proper implementation. Example

Here is an example of a Custom Hook that performs a generic HTTP request using TypeScript and React. This Hook handles the logic to make the request and handle the load status, data and errors.

import { useState, useEffect } from 'react';
import axios, { AxiosResponse, AxiosError } from 'axios';

type ApiResponse<T> = {
  data: T | null;
  loading: boolean;
  error: AxiosError | null;
};

function useFetch<T>(url: string): ApiResponse<T> {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<AxiosError | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response: AxiosResponse<T> = await axios.get(url);
        setData(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();

    // Cleanup function
    return () => {
      // Cleanup logic, if necessary
    };
  }, [url]);

  return { data, loading, error };
}

// Using the Custom Hook on a component
function ExampleComponent() {
  const { data, loading, error } = useFetch<{ /* Expected data type */ }>('https://example.com/api/data');

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  if (!data) {
    return <div>No data.</div>;
  }

  return (
    <div>
      {/* Rendering of the obtained data */}
    </div>
  );
}

export default ExampleComponent;

In this example, the Custom Hook useFetch takes a URL as an argument and performs a GET request using Axios. It manages the load status, data and errors, returning an object with this information.

The ExampleComponent component uses the Custom Hook useFetch to fetch data from an API and render it in the user interface. Depending on the status of the request, a load indicator, an error message or the fetched data is displayed.

There are many ways to use this pattern, in this link you can find several examples of custom Hooks to solve specific problems, the uses are many.

Where Find Me

Linkedin GitHub

brunosduarte
brunosduarte commented 3 weeks ago

Great post!

This seems to be a great post!

if (post === 'great') {
  return true
}