MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Optimistic Like Button with Explanation

ReactJS Hard State Management 19 views
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.
Back to Questions

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).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next