Takeaway from my first React interview

 Recently I got my first react interview, the question is not very hard, but it's something never brought up in my company. So I think it's worth to keep a record here.

All I need to do for the interview was to create an auto complete search box component. Simple workflow, fetch a call and return a list of data as suggestion, the only thing I want to talk about is the debounce, so it will only fire a call when user stop typing.


Here is an example with debounce method from lodash

import React, {useState, useRef} from "react";
import _ from "lodash";
const sendQuery = (query) => console.log(`Querying for ${query}`);const Search = () => {
const [userQuery, setUserQuery] = useState("");
const delayedQuery=useRef(_.debounce(q=>sendQuery(q),500)).current;
const onChange = e => {
setUserQuery(e.target.value);
delayedQuery(e.target.value);
};
return (
<div>
<label>Search:</label>
<input onChange={onChange} value={userQuery} />
</div>
);
}


Make sure to use useRef, otherwise it wouldn't work as expected!


The following functions are how debounce and throttle work behind the scene.

function debounce(fn, time) {
  let timer = null
  return () => {
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn, time)
  }
}


function throttle(fn, time) {
  let oldTime = 0
  return () => {
    const newTime = new Date()
    if (newTime - oldTime >= wait) {
      fn()
      oldTime = newTime
    }
  }
}


Comments