Calling Functions Inside JSX
What you'll learn: How to invoke functions directly within your JSX and when that code actually runs.
The Core Idea
You can call any JavaScript function inside curly braces in JSX, and it will execute immediately during render. This is different from passing a function reference — when you add parentheses (), you're telling React to run that function right now and use its return value.
function getGreeting() {
return "Hello, world!";
}
function App() {
return <h1>{getGreeting()}</h1>; // Function called at render time
}
Every time this component renders, getGreeting() executes and its result ("Hello, world!") gets inserted into the JSX.
When Functions Execute
Think of JSX rendering like reading a recipe aloud. When you hit {getGreeting()}, you don't just say "getGreeting" — you perform the action and announce the result. The function runs during the render, not before and not after.
function formatPrice(cents) {
return `$${(cents / 100).toFixed(2)}`;
}
function Product() {
return (
<div>
<p>Price: {formatPrice(2999)}</p> {/* Runs now, displays "$29.99" */}
<p>Tax: {formatPrice(500)}</p> {/* Runs again, displays "$5.00" */}
</div>
);
}
Each call happens fresh with each render. If your component re-renders, those functions execute again.
Common Use Cases
Helper functions for formatting, calculations, or transforming data are perfect candidates for direct calls inside JSX expressions.
Key Takeaway: Calling a function with parentheses () inside JSX curly braces executes it immediately during render and uses its return value in your UI.