Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

429
Vistas
How to solve setState is always one step behind on React JS

I am a beginner. I am learning react js. I am having an problem. setState is always one step behind.

Here is a sample:

enter image description here

Here, when I typed i then the console is showing nothing. Next, when I typed the m it shows i and as it is one step behind.

I have created two functions named handleChange and handleKeyword. The functions are behaving the same. I searched on the internet and got useEffect() suggestion to solve the problem but that has not solved my problem or I can't properly implement it.

Here is my codes:

Home.jsx

import React, { useState, useEffect } from 'react';
import Search from '../../components/searchBar/Search';
import './home.scss';

const Home = () => {
  const [search, setSearch] = useState('');
  const [keyword, setKeyword] = useState('');

  const handleChange = event => {
    setSearch(event.target.value);
    console.log('Search: ', search);
  };

  const handleKeyword = () => {
    setKeyword(search);
    console.log('Keyword:', keyword);
  };

  return (
    <div className="container pb-5">
      <Search
        handleChange={handleChange}
        handleKeyword={handleKeyword}
        keyword={keyword}
      />
    </div>
  );
};

export default Home;

Search.jsx

import React from 'react';
import './search.scss'

const Search = props => {
  return (
    <div className="d-flex input-group justify-content-center">
      <input
        type="text"
        className="form-control searchBox"
        placeholder="Search for copyright free images & videos..."
        value={props.value}
        onChange={event => props.handleChange(event)}
      />
      <button className="btn btn-primary" onClick={() => props.handleKeyword()}>
        Search
      </button>
    </div>
  );
};

export default Search;

How can I solve the problem?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

In Home.jsx, you can move the console statments inside useEffect with states search and keyword as dependencies to get the updated values. This issue is because react is declarative in nature so it decides when to setState runs. It can even be batched together for performance optimisations. So useEffect can be used in such cases to listen to change in states.

import React, { useState, useEffect } from 'react';
import Search from '../../components/searchBar/Search';
import './home.scss';

const Home = () => {
  const [search, setSearch] = useState('');
  const [keyword, setKeyword] = useState('');

  useEffect(() => {
     console.log('Search: ', search);
     console.log('Keyword:', keyword);
   }, [search, keyword])

  const handleChange = event => {
    setSearch(event.target.value);
   };

  const handleKeyword = () => {
    setKeyword(search);
   };

  return (
    <div className="container pb-5">
      <Search
        handleChange={handleChange}
        handleKeyword={handleKeyword}
        keyword={keyword}
      />
    </div>
  );
};

export default Home;
about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem is setState just promise you that value will be updated It does not affect your code, just move console.logs outside handleClicks

So, when you set a new state and you will see a new value only after rerender component.

  const handleKeyword = () => {
    setKeyword(search);
    console.log("Keyword:", keyword);
  };

  console.log("Keyword:2", keyword);

console.log("Keyword:", keyword); will be called in the first render with the old value console.log("Keyword:2", keyword); will be called in the second render with a new value.

about 4 years ago · Juan Pablo Isaza Denunciar

0

setState is async so changes to the state are not applied immediately. see here https://reactjs.org/docs/react-component.html#setstate

enter image description here

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda