مقابلات العمل2:47
مقابلات العمل · مبرمج · متقدّم
مقابلة مطوّر واجهة أمامية: البحث عن خطأ في React وقائمة بطيئةFrontend Developer: A Bug Hunt in React and a Slow List
- Mariam
- Hossam
0:00 / 2:47
النص
- MariamHi Hossam. I'll share a small component on screen. It has a few problems. Please read it aloud and tell me what you notice. There's no rush.
- HossamSure. Let me read it first. It's a timer component. It uses state for a count and starts a timer in an effect.
- MariamRight. The count should go up by one every second, but it stays at one. Why?
- HossamI think it's a stale closure. The effect runs once, with an empty dependency array, so the timer callback always sees the first value of the count, which is zero. It sets it to one each time.
- MariamHow would you fix it?
- HossamThe simplest fix is to use the functional form of the setter, so it uses the previous value: set count to previous plus one. Then the effect doesn't need the count in its dependencies. I'd also return a cleanup function that clears the timer.
- MariamWhy is the cleanup important?
- HossamWithout it, the timer keeps running after the component is removed, which can cause memory leaks and wasted work. In development with strict mode, you may also see the effect run twice, and a cleanup avoids two timers.
- MariamGood. Now look at the list below. It shows a hundred tasks and each one has a checkbox. What do you notice?
- HossamThe list items don't have a key prop. React will warn about it, and it also makes updates unpredictable. If the list is reordered, the state of one item might appear on another.
- MariamWhat would you use as the key?
- HossamA stable unique ID from the data, like the task ID. I wouldn't use the array index if the list can change order or items can be deleted.
- MariamNow the list feels slow when you tick one box. Why might that be?
- HossamThe parent keeps all tasks in one state, so ticking one box re-renders the parent and all hundred children. First I'd measure with the profiler to confirm. If it's the problem, I'd wrap the item component in memo and make sure the props don't change on every render, for example by keeping the handler stable.
- MariamAnd if the list had ten thousand items?
- HossamThen I'd consider virtualization, which only renders the rows visible on the screen. There are libraries for that. I've used one in a dashboard, but I'd test it with the accessibility tools, because it can affect keyboard navigation.
- MariamThat's a thorough answer. Anything you'd like to ask me?
- HossamYes. How does the team review pull requests, and how long does a typical review take?
- MariamTwo reviewers, usually within a day. Thanks, Hossam. I'll send feedback by Friday.