[React] React에서 검색기능 구현하기 (코드 리팩토링)

Chloe K·2022년 10월 26일
0
post-thumbnail

리액트 검색 기능 구현

✍️ 내가 짠 코드


const [inputValue, setInputValue] = useState("");

const filtering = () => {
    return inputValue === ''
      ? []
      : products.filter(product =>
          product.name.toLowerCase().includes(inputValue.toLowerCase())

❗️ 멘토님께 받은 코드리뷰

  • 변수(함수)명은 동사 + 명사로 짓는게 좋다. (변수명만으로도 무슨 기능을 하는지 파악이 가능해야 함!)
    filtering -> filterProducts
  • 삼항연산자를 사용하는 것 보다 if 문을 활용한다.
  • state에 의존해 있는 computed 값들은 함수보다 변수로 할당하는 것이 좋다.

📌 Refactoring

const filterProducts = (inputValue) => {
    if(!inputValue) return [];
    return products.filter(product =>
          product.name.toLowerCase().includes(inputValue.toLowerCase())

// query는 input value

Re-refactoring

const filteredProducts = products.filter(product =>   
    product.name.toLowerCase().includes(inputValue.toLowerCase()))
profile
Frontend Developer

0개의 댓글