useEffect makes onChange and typing lag/slow


I am creating a website where the user can type what he is looking for in a search bar.

Initially, I had a problem with the fact that onChange was one character behind the user search. For example, if the user search for “banana”, the search was “banan”.
I understood that the problem comes form the fact that setState is asynchronous.
onChange is one character on delay – Hooks

To avoid this problem, I introduced the useEffect component in my code. It works.
However now, if the user types some words, the words he types are not displayed immediately inside the search bar. They are displayed after few moments, as if it were a delay between what the user types and what it is displayed.

My searchbar component

export default function SearchBar({handlerSearchBar}) {
    const classes = useStyles();
    const [searchBarQuery, setSearchBarQuery] = React.useState([""])

    function handleChange(event) {

    useEffect(() => {
        console.log("Search message inside useEffect: ", searchBarQuery);

    return (
        <form className={classes.container} noValidate autoComplete="off">
                style={{ marginLeft: 40, marginRight: 40 }}
                placeholder="Write your query"
                // helperText="The results will appear below!"
                    shrink: true,


handlerSearchBar function

It a function that is passing the results from my search-bar component to its parents and then, to its grandparents (SearchForm).

The grandparents SearchForm is setting one of its state to what is passed via the searchbar handlerSearchBar function:

function SearchForm() {
    const [searchBarQueryParent, setSearchBarQueryParent] = React.useState([""])

    function handlerSearchBar(searchBarQuery) {
    return (something)

My question is: why is the display of the search words so much delayed than the their actual typing?

I think what is happening is that useEffect is called for each key stroke, and that is what it is so slow.
I tried to call useEffect on onSubmit but there is no improvement.

Or it is my handlerSearchBar function that makes everything slow


I resolved it by changing from onChange to onBlur.

I am not totally sure why the change works, but it does work.

Answered By – Magofoco

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published