Writing Compelling Usage Examples
Learn how to write usage examples that developers actually read. Covers the progressive disclosure pattern, runnable examples, expected output, and edge case documentation.
Detailed Explanation
Writing Usage Examples That Developers Love
The Usage section is the most-read part of any README after the title. Developers skim READMEs looking for code they can copy-paste and modify. Great usage examples follow the progressive disclosure pattern: start simple, then build complexity.
The Progressive Disclosure Pattern
Level 1: Minimal Working Example (3-5 lines)
import { compress } from 'my-compressor';
const output = compress('Hello, World!');
console.log(output); // "eJxLSS0u0S1OTgYABZwB9Q=="
This is the "hello world" of your library. It should work with zero configuration.
Level 2: Common Use Case (10-15 lines)
import { compress, decompress } from 'my-compressor';
// Compress with options
const compressed = compress(largeString, {
level: 9,
format: 'gzip',
});
// Decompress
const original = decompress(compressed);
console.log(original === largeString); // true
Level 3: Advanced Configuration (15-30 lines)
Show streaming, error handling, or integration with frameworks.
Show Expected Output
Always show what the code produces:
const result = parse('2024-01-15T10:30:00Z');
console.log(result);
// {
// year: 2024,
// month: 1,
// day: 15,
// hour: 10,
// minute: 30,
// timezone: 'UTC'
// }
Use Realistic Data
Avoid foo, bar, and test123. Use realistic examples:
// Bad
const result = process('abc');
// Good
const result = process('user@example.com');
Error Handling
Show how errors are communicated:
try {
const result = parse('invalid-input');
} catch (error) {
console.error(error.message);
// "Invalid format: expected ISO 8601 date string"
}
Framework Integration
If your library integrates with popular frameworks, show how:
// Next.js API Route
export async function GET(request: Request) {
const data = await myLibrary.fetch(request.url);
return Response.json(data);
}
Use Case
Improving the usage documentation for a library or tool to reduce support questions and make it easier for developers to get started with real-world code examples.