Go Back

5 min read

Next.js TypeScript Folder Guide

profile

Nitin k

|

November 04, 2024

views

Alt text for the image

When working on a Next.js project with TypeScript, organizing your folder structure can significantly improve your development experience. In this guide, we will delve into three essential folders: Hooks, Lib, and Utilities. We'll explore the purpose of each folder, the types of functions you should include, and best practices for TypeScript file extensions.

Hooks, Lib & Utilities: What Functions to Write?

1. Hooks Folder

Purpose

The Hooks folder is designated for custom hooks that are reusable across your project. Hooks encapsulate logic and stateful operations related to specific features or behaviors, managing complex tasks like handling scrolling, fetching data, or managing the viewport.

Functions to Write

  • State and Side-effect Management: These custom hooks manage complex state and side-effects.
    • useFetchData: Manages API calls and data fetching.
    • useOnScreen: Detects when elements are visible in the viewport.
    • useTheme: Toggles between light and dark themes.
  • Event Management: Handles specific events.
    • useDebounce or useThrottle: Rate-limits operations like input or scroll events.
    • useWindowResize or useScroll: Handles browser window events.
  • DOM Interaction: Manages or manipulates DOM elements.
    • useClickOutside: Handles clicks outside a specified element.
    • useLocalStorage: Saves or retrieves data from localStorage.

2. Lib Folder

Purpose

The Lib (or Library) folder typically holds utility functions and configurations related to third-party libraries or modules used across the app. This includes custom API setup, configurations, or helper functions for external libraries.

Functions to Write

  • API Configuration and Wrappers: Functions that interface with APIs or third-party services.
    • apiClient: Sets up your base Axios instance.
    • authProvider: Handles custom authentication.
    • firebaseConfig or supabaseClient: Manages third-party integrations.
  • Utility Wrappers: Simplifies library usage across the app.
    • analytics functions: Wraps calls to analytics providers.
    • dateFormatter: Uses date-fns or moment.js for consistent date formatting.
  • Global Error Handling: Manages or logs errors across API requests or third-party service interactions.

3. Utilities Folder

Purpose

The Utilities folder (or Utils) holds reusable helper functions that aren’t tied to a specific feature, UI, or third-party library. These are general-purpose functions that help simplify code throughout the app.

Functions to Write

  • General Helpers: For common data manipulation tasks.
    • capitalizeFirstLetter or slugify: Manages string manipulations.
    • formatCurrency: Formats numbers.
    • arrayUnique: Removes duplicates from arrays.
  • Reusable Logic: Handles commonly needed calculations or transformations.
    • calculateDistance or formatTimeAgo: Processes data for display.
    • debounce or throttle: Limits the rate of function execution.
  • Type Checkers: Ensures data types and validations.
    • isEmptyObject: Checks if an object is empty.
    • isValidEmail: Validates email input.

Each of these folders helps organize your project by encapsulating logic into reusable, maintainable parts—Hooks for stateful logic, Lib for library-related setup, and Utilities for general-purpose helpers.

Where to Place type.ts?

For a type.ts file, the best location depends on how the types are being used:

  1. Project-wide Types: If the types are global or shared across the entire project (like API response types, common data shapes, or enums), placing type.ts in a root-level folder like types or even the root of the Lib folder can keep things centralized.
  2. Feature-specific Types: If the types are specific to a certain part of your app (e.g., types only for a form component), it’s better to nest them closer to the component or feature that uses them.

Generally, for centralized types that multiple files reference, storing type.ts in Lib helps make them easy to import and keeps the project structure clean.

File Extensions: .ts or .tsx?

Here’s a guide on which extensions to use for files in each folder:

1. Hooks Folder

  • Use .ts or .tsx?: Typically, .ts.
  • When to Use .ts: Most custom hooks do not include JSX and only handle logic, so .ts is generally sufficient.
  • When to Use .tsx: If your hook involves rendering any JSX elements (e.g., a hook that returns a UI component or renders child components), then use .tsx.

2. Lib Folder

  • Use .ts or .tsx?: Mostly .ts.
  • When to Use .ts: Files in Lib usually contain setup configurations, API instances, and functions without JSX, so .ts is standard.
  • When to Use .tsx: Rarely needed. Only use .tsx if your Lib folder includes files that render UI elements (uncommon in Lib folders).

3. Utilities Folder

  • Use .ts or .tsx?: Typically, .ts.
  • When to Use .ts: Utility functions are generally non-UI-related, so .ts is sufficient.
  • When to Use .tsx: If there’s a utility that generates JSX elements, use .tsx, but this is unusual in utility files.

Summary

  • .ts: Standard for Hooks, Lib, and Utilities.
  • .tsx: Only if a file contains or returns JSX elements.

Conclusion

Organizing your Next.js project with TypeScript into well-defined folders like Hooks, Lib, and Utilities helps in maintaining clean, manageable, and scalable code. By understanding the purpose of each folder and the types of functions they should contain, you can create a more structured and efficient development environment. This guide should serve as a useful reference for setting up your project structure, ensuring that your codebase remains organized and easy to navigate.