Writing Code Examples That Teach
The difference between a confusing tutorial and an enlightening one often comes down to how code examples are presented. Let's explore how to write code that teaches.
Inline Code for Quick References
When mentioning code within a sentence, use inline formatting. For example, the useState hook returns an array with the current state and a setter function. You might destructure it as const [count, setCount] = useState(0).
Inline code works well for:
Variable names like
isLoadingoruserDataFunction names like
handleSubmit()File paths like
src/components/Button.tsxCLI commands like
npm install
Code Blocks for Complete Examples
When you need to show more than a single line, use a code block. Here's a simple React component:
function Greeting({ name }: { name: string }) {
return (
<div className="greeting">
<h1>Hello, {name}!</h1>
<p>Welcome to our application.</p>
</div>
);
}Notice how the code is indented consistently and includes just enough context to be useful without being overwhelming.
Show Before and After
When refactoring code, showing the transformation helps readers understand why a change matters. Here's a common pattern — extracting repeated logic:
Before:
// Repeated in multiple places
const formattedDate = new Date(timestamp)
.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});After:
// Reusable utility function
function formatDate(timestamp) {
return new Date(timestamp)
.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
}
// Usage is now simple and consistent
const formattedDate = formatDate(timestamp);Best Practices
Keep examples focused — one concept per snippet
Use realistic variable names —
usernotfooInclude comments when the code isn't self-explanatory
Test your examples — broken code breaks trust