
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.
useDebounceoruseThrottle: Rate-limits operations like input or scroll events.useWindowResizeoruseScroll: Handles browser window events.
- DOM Interaction: Manages or manipulates DOM elements.
useClickOutside: Handles clicks outside a specified element.useLocalStorage: Saves or retrieves data fromlocalStorage.
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.firebaseConfigorsupabaseClient: Manages third-party integrations.
- Utility Wrappers: Simplifies library usage across the app.
analyticsfunctions: Wraps calls to analytics providers.dateFormatter: Usesdate-fnsormoment.jsfor 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.
capitalizeFirstLetterorslugify: Manages string manipulations.formatCurrency: Formats numbers.arrayUnique: Removes duplicates from arrays.
- Reusable Logic: Handles commonly needed calculations or transformations.
calculateDistanceorformatTimeAgo: Processes data for display.debounceorthrottle: 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:
- 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.tsin a root-level folder liketypesor even the root of theLibfolder can keep things centralized. - 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
.tsor.tsx?: Typically,.ts. - When to Use
.ts: Most custom hooks do not include JSX and only handle logic, so.tsis 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
.tsor.tsx?: Mostly.ts. - When to Use
.ts: Files inLibusually contain setup configurations, API instances, and functions without JSX, so.tsis standard. - When to Use
.tsx: Rarely needed. Only use.tsxif yourLibfolder includes files that render UI elements (uncommon inLibfolders).
3. Utilities Folder
- Use
.tsor.tsx?: Typically,.ts. - When to Use
.ts: Utility functions are generally non-UI-related, so.tsis 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, andUtilities. - .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.