frontend-challenges
frontend-challenges copied to clipboard
re-render 3
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:
- The SearchBar is memoized using React.memo, yet it still re-renders every time the parent component updates. Why does this happen?
- What is causing the memoization of SearchBar to fail, and how would you resolve the issue?
- Modify the code so that SearchBar only re-renders when it truly needs to, without breaking the functionality of the search feature.
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;
#175 - Pull Request updated.