Render Count Tracker
ReactJS
Medium
5 views
Problem Description
Track how many times a component re-rendered and show it on screen.
Output Format
Render a React component.
Constraints
Use a ref that increments on every render.
Official Solution
import React, { useRef, useState } from 'react';
function CounterCard({ value }) {
const renders = useRef(0);
renders.current += 1;
return (
<div style={{ border: '1px solid #eee', borderRadius: 14, padding: 12 }}>
<strong>meetcode render tracker</strong>
<div style={{ marginTop: 6, color: '#555' }}>Value: {value}</div>
<div style={{ marginTop: 6, color: '#555' }}>Renders: {renders.current}</div>
</div>
);
}
export default function App() {
const [value, setValue] = useState(0);
const [text, setText] = useState('');
return (
<div style={{ padding: 16, width: 520 }}>
<CounterCard value={value} />
<div style={{ display: 'grid', gap: 10, marginTop: 12 }}>
<button type='button' onClick={() => setValue((v) => v + 1)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Increment</button>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder='Typing here also re-renders' style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!