ReactJS Program to Optimistic Like Button with Explanation
ReactJS
Hard
State Management
19 views
1 min read
88 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around like, button, update. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a like button that updates UI immediately and then confirms.
Input Format
No input.
Output Format
Render a React component.
Constraints
Update state first, then simulate server with a delay.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react';
function wait(ms) {
return new Promise((r) => setTimeout(r, ms));
}
export default function App() {
const [likes, setLikes] = useState(10);
const [status, setStatus] = useState('');
async function like() {
setLikes((n) => n + 1);
setStatus('Saving...');
await wait(600);
setStatus('Saved on meetcode.');
await wait(700);
setStatus('');
}
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode post</h2>
<div style={{ color: '#555' }}>Likes: {likes}</div>
<button type='button' onClick={like} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Like</button>
{status ? <div style={{ marginTop: 10, color: '#555' }}>{status}</div> : null}
</div>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create a like button that updates UI immediately and then confirms.
Input / Output
Output
Render a React component.
Constraints
Update state first, then simulate server with a delay.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
import React, { useState } from 'react';
function wait(ms) {
return new Promise((r) => setTimeout(r, ms));
}
export default function App() {
const [likes, setLikes] = useState(10);
const [status, setStatus] = useState('');
async function like() {
setLikes((n) => n + 1);
setStatus('Saving...');
await wait(600);
setStatus('Saved on meetcode.');
await wait(700);
setStatus('');
}
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode post</h2>
<div style={{ color: '#555' }}>Likes: {likes}</div>
<button type='button' onClick={like} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Like</button>
{status ? <div style={{ marginTop: 10, color: '#555' }}>{status}</div> : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!