jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
45 stars 5 forks source link

re-render 3 #174

Open jsartisan opened 1 month ago

jsartisan commented 1 month ago

Info

difficulty: easy
title: re-render 3
type: question
template: react
tags: css, html, javascript

Question

Consider the app that renders a SearchBar component, which is memoized using React.memo. The SearchBar accepts an onSearch function as a prop to update the search query.

Can you answer the following:

Template

styles.css

body {
  font-family: sans-serif;
}

h1 {
  font-size: 1.5rem;
}

App.jsx

import SearchBar from "./SearchBar";
import React, { useState } from "react";

function App() {
  const [query, setQuery] = useState("");
  const [items] = useState(["Apple", "Banana", "Orange", "Grapes"]);

  const handleSearch = (searchTerm) => {
    setQuery(searchTerm);
  };

  const filteredItems = items.filter((item) =>
    item.toLowerCase().includes(query.toLowerCase()),
  );

  return (
    <div>
      <SearchBar onSearch={handleSearch} />
      <ul>
        {filteredItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

index.jsx

import React, { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";

import App from "./App";

const root = createRoot(document.getElementById("root"));
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

public/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

SearchBar.jsx

import { memo } from 'react';

const SearchBar = memo(({ onSearch }) => {
  console.log('SearchBar rendered');

  return (
    <input 
      type="text" 
      placeholder="Search..." 
      onChange={(e) => onSearch(e.target.value)} 
    />
  );
});

export default SearchBar;
github-actions[bot] commented 1 month ago

175 - Pull Request updated.