Keep Mutable Value In Ref
ReactJS
Hard
5 views
Problem Description
Use useRef to store a mutable value without re-rendering.
Output Format
Render a React component.
Constraints
Store click count in ref and show it when asked.
Official Solution
import React, { useRef, useState } from 'react';
export default function App() {
const clicksRef = useRef(0);
const [shown, setShown] = useState(0);
function click() {
clicksRef.current += 1;
}
function show() {
setShown(clicksRef.current);
}
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode ref counter</h2>
<button type='button' onClick={click} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Click</button>
<button type='button' onClick={show} style={{ marginLeft: 10, padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Show</button>
<div style={{ marginTop: 10, color: '#555' }}>Shown clicks: {shown}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!