Here are some good ways to structure a React project and separate logic from components:
1. Organized Folder Structure
/src
/components # Reusable UI components
/pages # Page-specific components
/hooks # Custom hooks for reusable logic
/contexts # Context API for global state
/services # API calls, authentication logic
/utils # Utility functions
/store # Redux/Zustand store (if used)
/styles # Global styles
/assets # Images, icons, fonts
2. Separate Logic Using Custom Hooks
// hooks/useFetch.js
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data));
}, [url]);
return data;
};
export default useFetch;
3. Use Context API or State Management
Avoid prop drilling by using React Context or Redux/Zustand.
4. Move API Calls to a Separate Service Layer
// services/api.js
export const fetchUsers = async () => {
const response = await fetch("/api/users");
return response.json();
};
5. Utility Functions for Reusable Logic
// utils/formatDate.js
export const formatDate = (date) => new Date(date).toLocaleDateString();