-1

I know I'm missing something just can't figure out what it is. I have the following component:

const SearchComponent = (props) => {
  const [searchValue, setSearchValue] = useState('');

  const searchInputHandler = e => {
    const inputValue = e.target.value;
    setSearchValue(inputValue);
    console.log(searchValue);
    // filterData(searchValue, props)
  }

  return (
    <>
    <Col className="col-sm-6" style={styles.flex}>
      <InputGroup>
        <Input
          placeholder="Search"
          onChange={e => searchInputHandler(e)}
          value={searchValue}
          />
        <InputGroupAddon addonType="append">
          <Button style={styles.inputButton} color="info">Clear</Button>
        </InputGroupAddon>
      </InputGroup>
    </Col>
    </>
  )
};

in the above component the initial value of my Input is ' '. When I type any letter let's say a "t".

I would expect that searchValue would = "t" since I am running setSearchValue(inputValue) in my method. However when I type in "t" the state stays the same. Only after I type it the second time then it would show ' t'. What am I missing here?

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
FabricioG
  • 3,107
  • 6
  • 35
  • 74

1 Answers1

2

setState is asynchronous.

See When is setState asynchronous?

Currently, setState is asynchronous inside event handlers.

Why doesn’t React update this.state synchronously?

React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.

Therefore, logging console.log(searchValue); right after setSearchValue(inputValue); will log the value of searchValue in the current render (or "in the current scope").

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118