← Back to Blog
Tutorial12 min readOctober 15, 2025

Using Mock Data in React Applications: Complete Guide

Learn how to effectively use mock data in React for faster development, better testing, and more reliable applications.

Why Use Mock Data in React?

When building React applications, waiting for backend APIs to be ready can slow down frontend development significantly. Mock data allows you to develop and test your components independently, iterate faster, and catch UI issues early in the development cycle.

Whether you're building a new feature, writing component tests, or creating a demo, mock data is an essential tool in the modern React developer's toolkit.

Method 1: Simple Static Mock Data

The simplest approach is to create a separate file with static mock data. This works great for predictable, repeatable testing scenarios.

// mockData/users.js
export const mockUsers = [
  {
    id: "1",
    name: "John Doe",
    email: "john@example.com",
    avatar: "https://i.pravatar.cc/150?img=1",
    role: "Developer"
  },
  {
    id: "2",
    name: "Jane Smith",
    email: "jane@example.com",
    avatar: "https://i.pravatar.cc/150?img=2",
    role: "Designer"
  }
];
// components/UserList.jsx
import { mockUsers } from '../mockData/users';

function UserList() {
  const [users, setUsers] = useState(mockUsers);

  return (
    <div>
      {users.map(user => (
        <div key={user.id}>
          <img src={user.avatar} alt={user.name} />
          <h3>{user.name}</h3>
          <p>{user.email}</p>
        </div>
      ))}
    </div>
  );
}

Method 2: Using Environment Variables

For production-ready code, use environment variables to switch between real and mock data sources. This allows you to easily toggle mock data on and off without changing your code.

// services/userService.js
const USE_MOCK_DATA = process.env.REACT_APP_USE_MOCK_DATA === 'true';

export async function fetchUsers() {
  if (USE_MOCK_DATA) {
    // Return mock data
    return Promise.resolve(mockUsers);
  }

  // Make real API call
  const response = await fetch('/api/users');
  return response.json();
}

Then in your .env file:

REACT_APP_USE_MOCK_DATA=true

Method 3: Custom Hooks for Mock Data

Create a custom hook that generates fresh mock data on demand. This approach is great for testing edge cases and different data scenarios.

// hooks/useMockUsers.js
import { useState, useEffect } from 'react';

function generateMockUser(id) {
  return {
    id: String(id),
    name: `User ${id}`,
    email: `user${id}@example.com`,
    avatar: `https://i.pravatar.cc/150?img=${id}`,
    joinedDate: new Date().toISOString()
  };
}

export function useMockUsers(count = 10) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Simulate API delay
    setTimeout(() => {
      const mockUsers = Array.from({ length: count }, (_, i) =>
        generateMockUser(i + 1)
      );
      setUsers(mockUsers);
      setLoading(false);
    }, 500);
  }, [count]);

  return { users, loading };
}
// components/UserList.jsx
import { useMockUsers } from '../hooks/useMockUsers';

function UserList() {
  const { users, loading } = useMockUsers(20);

  if (loading) return <p>Loading...</p>;

  return (
    <div>
      {users.map(user => (
        <UserCard key={user.id} user={user} />
      ))}
    </div>
  );
}

Method 4: Integration with Mock Data Generator

For more realistic data, use a mock data generator tool to create comprehensive datasets, then import them into your React app.

Pro Tip:

Use our free mock data generator to create realistic test data with 60+ data types. Generate once, save as JSON, and import into your React project!

// 1. Generate data using our tool with this schema:
{
  "id": "uuid",
  "name": "name",
  "email": "email",
  "phone": "phone",
  "avatar": "avatar",
  "company": "company",
  "jobTitle": "jobTitle",
  "createdAt": "past"
}

// 2. Save as mockData/users.json

// 3. Import and use in your component:
import mockUsers from '../mockData/users.json';

function UserDashboard() {
  const [users] = useState(mockUsers);

  return (
    <div>
      <h1>Total Users: {users.length}</h1>
      {users.map(user => (
        <UserCard key={user.id} user={user} />
      ))}
    </div>
  );
}

Testing Components with Mock Data

Mock data is essential for component testing. Here's how to use it with React Testing Library:

// UserList.test.js
import { render, screen } from '@testing-library/react';
import UserList from './UserList';

const mockUsers = [
  {
    id: '1',
    name: 'Test User',
    email: 'test@example.com'
  }
];

test('renders user list', () => {
  render(<UserList users={mockUsers} />);

  expect(screen.getByText('Test User')).toBeInTheDocument();
  expect(screen.getByText('test@example.com')).toBeInTheDocument();
});

test('handles empty user list', () => {
  render(<UserList users={[]} />);

  expect(screen.getByText('No users found')).toBeInTheDocument();
});

Best Practices

1. Keep Mock Data Separate

Store mock data in a dedicated mockData/ or__mocks__/ folder. This keeps your codebase organized and makes it easy to find and update test data.

2. Match Real Data Structure

Ensure your mock data matches the exact structure of your API responses. This prevents issues when switching to real data.

3. Use TypeScript Interfaces

Define TypeScript interfaces for your data models. This ensures type safety for both mock and real data.

4. Test Edge Cases

Create mock data for edge cases like empty arrays, null values, very long strings, and special characters to ensure your components handle all scenarios gracefully.

5. Don't Commit Large Mock Files

For large datasets, generate mock data on-the-fly or use a small representative sample in version control.

Common Pitfalls to Avoid

  • Hardcoding mock data in components: This makes testing harder and couples your component to specific data.
  • Forgetting to remove mock data imports: Use environment variables or build-time flags to ensure mock data doesn't reach production.
  • Using unrealistic data: Mock data that's too simple won't catch real-world issues like layout breaks with long names.
  • Not updating mock data: When your API changes, update your mock data to match the new structure.

Need Realistic Mock Data?

Generate production-quality mock data instantly with our free tool. Perfect for React development and testing!

Generate Mock Data Now →

Conclusion

Mock data is an essential tool for React developers. Whether you're building new features, writing tests, or creating demos, having quality mock data accelerates development and improves code quality.

Choose the method that best fits your needs - from simple static data for quick tests to sophisticated generators for comprehensive testing scenarios. The key is to use mock data consistently and keep it in sync with your real data structures.