Chat
People often complain about interviews: “Interview to build rockets and screw screws for work.”, thus expressing the current situation of different matching requirements for work content and ability.
It is not ruled out that some companies want to investigate the candidate's technical limits or comprehensive technical capabilities, hoping to obtain a talent with higher scalability. Some companies also don’t know how to screen candidates, so they just find some online interview questions, various principles, and details. It’s not that these things are not good, but I think the first thing to do is to check whether the candidate is competent for the position. At the same time, if he can understand the principles and details, it will naturally be the icing on the cake.
After chatting, I think I can test my actual ability.How to implement a countdown component。
Countdown Components - Requirements Description:
Write a functional component CountDown, set a property that passes in the maximum value, decrementing one every second until it is 0.
question
- How to design.
import { useState } from "react" function CountDown({max = 10}){ const [count,setCount] = useState(max) useEffect(()=>{ if(count>0){ setTimeout(()=>{ setCount(count-1) },1000) } }) return <h1>{count}</h1> } export default CountDown
- What if I want to reset the count after the parent changes the prop?
Let's use another useEffect to process:
import { useState } from "react" function CountDown({max = 10}){ const [count,setCount] = useState(max) // Countdown logic useEffect(()=>{ if(count>0){ setTimeout(()=>{ setCount(count-1) },1000) } }) // Reset count useEffect(()=>{ setCount(max) },[max]) return <h1>{count}</h1> } export default CountDown
- How do we deal with setTimeout that may cause memory leakage?
Processed through the useEffect return function.
import { useState } from "react" function CountDown({max = 10}){ const [count,setCount] = useState(max) // Countdown logic useEffect(()=>{ let timer = null; if(count>0){ timer = setTimeout(()=>{ setCount(count-1) },1000) } return ()=>{ clearTimeout(timer) } }) // Reset count useEffect(()=>{ setCount(max) },[max]) return <h1>{count}</h1> } export default CountDown
at last
A simple component still contains many knowledge points, which can not only examine the candidate's basic technical ability, but also examine his logical thinking ability.
This is the article about the countdown component of React classic interview questions. For more related React countdown component content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!