Creating a scalable and maintainable React application involves properly structuring your codebase and adhering to the separation of concerns principle. In this example, we'll build a simple 3-tier React application using TypeScript, React Query for data fetching, Jotai for state management, and React for the UI. The three tiers are:
- Data Layer: Responsible for data fetching using React Query.
- Business Logic Layer: Manages application state and business logic using Jotai.
- UI Layer: Handles the presentation layer using React components.
We'll use a simple Todo application as our example.
Folder Structure
Organizing your codebase clearly is crucial. Here's a suggested folder structure:
src/
├── api/
│ ├── todos.ts
├── atoms/
│ ├── todosAtom.ts
├── components/
│ ├── TodoList.tsx
│ ├── AddTodo.tsx
├── types/
│ ├── index.ts
├── App.tsx
├── index.tsx
1. Define Types
First, define the data structures using TypeScript interfaces.
// src/types/index.ts
export interface Todo {
id: number;
title: string;
completed: boolean;
}
2. Data Layer with React Query
The data layer handles all API interactions. We'll use React Query to fetch, add, and toggle todos.
Setup React Query
First, install the necessary packages:
npm install react-query axios jotai
# or
yarn add react-query axios jotai
Wrap your application with QueryClientProvider:
// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from 'react-query';
import App from './App';
const queryClient = new QueryClient();
ReactDOM.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
document.getElementById('root')
);
API Functions
Create functions to interact with the backend API.
// src/api/todos.ts
import axios from 'axios';
import { Todo } from '../types';
const API_URL = 'https://jsonplaceholder.typicode.com/todos';
export const fetchTodos = async (): Promise<Todo[]> => {
const response = await axios.get<Todo[]>(API_URL);
return response.data.slice(0, 10); // Limiting to 10 for simplicity
};
export const addTodo = async (title: string): Promise<Todo> => {
const response = await axios.post<Todo>(API_URL, {
title,
completed: false,
});
return response.data;
};
export const toggleTodo = async (todo: Todo): Promise<Todo> => {
const response = await axios.put<Todo>(`${API_URL}/${todo.id}`, {
...todo,
completed: !todo.completed,
});
return response.data;
};
3. Business Logic Layer with Jotai
The business logic layer manages the state and encapsulates the business rules. Using Jotai, we can create atoms that interact with React Query.
Creating Atoms
// src/atoms/todosAtom.ts
import { atom } from 'jotai';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { fetchTodos, addTodo, toggleTodo } from '../api/todos';
import { Todo } from '../types';
// Atom to store the current filter (if needed)
export const filterAtom = atom<'all' | 'completed' | 'incomplete'>('all');
// Atom to manage todos
export const todosAtom = atom(async (get) => {
const { data } = await useQuery('todos', fetchTodos);
return data;
});
// Custom hooks for mutations
export const useAddTodo = () => {
const queryClient = useQueryClient();
return useMutation(addTodo, {
onSuccess: () => {
queryClient.invalidateQueries('todos');
},
});
};
export const useToggleTodo = () => {
const queryClient = useQueryClient();
return useMutation(toggleTodo, {
onSuccess: () => {
queryClient.invalidateQueries('todos');
},
});
};
Note: While Jotai is powerful for state management, integrating it directly with React Query is possible but typically you might keep React Query queries separate. However, for this example, we're integrating them within Jotai atoms for demonstration purposes.
4. UI Layer with React
The UI layer consists of React components that consume the state and trigger actions.
TodoList Component
// src/components/TodoList.tsx
import React from 'react';
import { useAtom } from 'jotai';
import { todosAtom, useToggleTodo } from '../atoms/todosAtom';
import { Todo } from '../types';
const TodoList: React.FC = () => {
const [todos] = useAtom(todosAtom);
const toggleMutation = useToggleTodo();
if (!todos) return <div>Loading...</div>;
const handleToggle = (todo: Todo) => {
toggleMutation.mutate(todo);
};
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.completed}
onChange={() => handleToggle(todo)}
/>
{todo.title}
</label>
</li>
))}
</ul>
);
};
export default TodoList;
AddTodo Component
// src/components/AddTodo.tsx
import React, { useState } from 'react';
import { useAtom } from 'jotai';
import { useAddTodo } from '../atoms/todosAtom';
const AddTodo: React.FC = () => {
const [title, setTitle] = useState('');
const addMutation = useAddTodo();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (title.trim()) {
addMutation.mutate(title);
setTitle('');
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={title}
placeholder="Add new todo"
onChange={(e) => setTitle(e.target.value)}
/>
<button type="submit">Add</button>
</form>
);
};
export default AddTodo;
App Component
// src/App.tsx
import React from 'react';
import TodoList from './components/TodoList';
import AddTodo from './components/AddTodo';
const App: React.FC = () => {
return (
<div style={{ padding: '2rem' }}>
<h1>Todo App</h1>
<AddTodo />
<TodoList />
</div>
);
};
export default App;
Coding Principles for Reusability and Clear Responsibility
-
Separation of Concerns: Each layer has a distinct responsibility.
- Data Layer: Handles API interactions.
- Business Logic Layer: Manages state and business rules.
- UI Layer: Presents data and captures user interactions.
-
Reusability:
- API Functions: Encapsulating API calls in separate functions allows them to be reused across different parts of the application.
- Atoms and Hooks: Creating custom hooks for mutations (
useAddTodo, useToggleTodo) allows reuse within any component.
- Components: Designing components like
TodoList and AddTodo to be modular and reusable.
-
Type Safety: Using TypeScript interfaces ensures that data structures are consistent, reducing bugs and improving developer experience.
-
Optimistic Updates and Caching: Leveraging React Query’s caching and invalidation ensures the UI remains in sync with the server state efficiently.
-
Atomic State Management: Using Jotai’s atoms for individual pieces of state promotes fine-grained control and reactivity.
-
Scalability: The 3-tier structure allows easy scaling as the application grows. New features can be added by extending the relevant layer without affecting others.
Enhancements and Best Practices
-
Error Handling: Implement error boundaries and handle API errors gracefully within your components.
// Example in TodoList
if (toggleMutation.isError) return <div>Error toggling todo</div>;
if (addMutation.isError) return <div>Error adding todo</div>;
-
Loading States: Provide visual feedback during data fetching or mutations.
// Example in AddTodo
<button type="submit" disabled={addMutation.isLoading}>
Add
</button>
-
Optimistic Updates: Improve user experience by updating the UI before the server confirms the mutation.
-
Modularization: As the app grows, consider further modularizing your code, such as separating hooks, utilities, and components into feature-specific directories.
-
Testing: Implement unit and integration tests to ensure each layer functions correctly.
Conclusion
This example demonstrates how to structure a React application using TypeScript, React Query, and Jotai while adhering to the separation of concerns principle. By clearly defining the responsibilities of each layer, you create a scalable and maintainable codebase that facilitates reusability and clarity.