Intl Formatter Outside Component

Intl Formatter Outside Component

Easy ReactJS Performance & Patterns 32 views
Explanation Complexity

Problem Statement

Create expensive Intl formatter once, not every render.

Input Format

No input.

Output Format

Render a React component.

Constraints

Move heavy objects (Intl/regex/maps) outside components when possible.

Input / Output Format

Input Format
No input.
Output Format
Render a React component.
Constraints
Move heavy objects (Intl/regex/maps) outside components when possible.

Examples

Input:
Output:
(React code)

Example Solution (Public)

ReactJS
import React, { useState } from 'react';

const money = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });

export default function App() {
  const [price, setPrice] = useState('199');

  const n = Number(price);
  const safe = Number.isFinite(n) ? n : 0;

  return (
    <div style={{ padding: 16, width: 520 }}>
      <h2 style={{ marginTop: 0 }}>meetcode pricing</h2>
      <input value={price} onChange={(e) => setPrice(e.target.value.replace(/\\D/g, ''))} inputMode='numeric' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
      <div style={{ marginTop: 10, color: '#555' }}>Formatted: {money.format(safe)}</div>
    </div>
  );
}

Official Solution Code

import React, { useState } from 'react';

const money = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });

export default function App() {
  const [price, setPrice] = useState('199');

  const n = Number(price);
  const safe = Number.isFinite(n) ? n : 0;

  return (
    <div style={{ padding: 16, width: 520 }}>
      <h2 style={{ marginTop: 0 }}>meetcode pricing</h2>
      <input value={price} onChange={(e) => setPrice(e.target.value.replace(/\\D/g, ''))} inputMode='numeric' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
      <div style={{ marginTop: 10, color: '#555' }}>Formatted: {money.format(safe)}</div>
    </div>
  );
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.