I have this React code:
import React, { useState, useEffect, useRef } from 'react';
import Card from '../UI/Card';
import './Search.css';
const Search = React.memo(props => {
const { onLoadIngredients } = props;
const [enteredFilter, setEnteredFilter] = useState('');
const inputRef = useRef();
useEffect(() => {
const timer = setTimeout(() => {
if (enteredFilter === inputRef.current.value) {
const query =
enteredFilter.length === 0
? ''
: `?orderBy="title"&equalTo="${enteredFilter}"`;
fetch(
'example-firebase-url.json' + query
)
.then(response => response.json())
.then(responseData => {
const loadedIngredients = [];
for (const key in responseData) {
loadedIngredients.push({
id: key,
title: responseData[key].title,
amount: responseData[key].amount
});
}
onLoadIngredients(loadedIngredients);
});
}
}, 500);
return () => {
clearTimeout(timer);
};
}, [enteredFilter, onLoadIngredients, inputRef]);
return (
<section className="search">
<Card>
<div className="search-input">
<label>Filter by Title</label>
<input
ref={inputRef}
type="text"
value={enteredFilter}
onChange={event => setEnteredFilter(event.target.value)}
/>
</div>
</Card>
</section>
);
});
export default Search;
It uses a search bar so that when user is typing something his results gets filtered by making requests to a firebase server after that user stopped typing for 500 milliseconds.
The thing I don’t understand is instructor says that enteredFilter
in useEffect
is a closure so it s the value setTimeout
locks, so it’s the old value and inputRef
is the current value so he compares the old value with the new one to see if the user stopped typing so the request can be made.
What I don’t understand is why inputRef
is not a closure as well? Clearly it is used in the check statement inside the setTimeout
function just like enteredFilter
so shouldn t this value also be enclosed just like enteredFilter
? That instructor says that inputRef
is not a closure because it’s defined outside of the closure, but as I see enteredFilter
is also defined outside the closure and used inside.
Can someone help me understand why this code works like this?