Help with UseState Hook in React

Goal : I am trying to set a value to a variable called selectedBreed which I have initialized to an empty string using the useState hook.

Problem: the selectBreed variable seems to remain empty even after I set to a value within the handleChange function. Can someone please tell me why.

function handleChange(value) {
    setSelectedBreed(value);  // am setting a value here
    console.log(value); // pitbull
    console.log(selectedBreed); // but here its empty
  }

console.log(selectedBreed); // pitbull 
//Outside of the function, it's set though

Is it actually updating the value in the component (ie ignoring the console logs, is it actually working as expected, is there actually a problem at all?). If it isn’t working can you show the code? It’s going to update the state, which causes the component to rerender. When it rerenders (ie the entire component function is called again) it will have the new value set.

// Outside of the function, it’s set though

The handler function isn’t called again until something triggers it. So the console will only show the current value for that log – you shouldn’t expect to see an updated value when the handler is called.

const Example = () => {
  const [value, setValue] = React.useState("");

  const handleChange(e) {
    setValue(e.target.value);
    console.log(value);
  }

  return (
    <>
      <input type="text" value={value} onChange={handleChange} />
      <p>{value}</>
    </>
  );
};
  • user makes first change to input (types “a”)
  • handler function called
  • setState called with value of input (“a”)
  • console logs "" (this is the initial value)
  • component rerenders, value in p element is “a”
  • user makes second change to input (types “b”
  • handler function called
  • setState called with value of input (“ab”)
  • console logs "a" (current value)
  • component rerenders, value in p element is “ab”
  • user makes third change to input (types “c”
  • handler function called
  • setState called with value of input (“abc”)
  • console logs "ab" (current value)
  • component rerenders, value in p element is “abc”

Do you see how the log is one behind each time? It’s logging what the state is at the point the handler is called, it can’t log anything else

1 Like

Hey @DanCouper, sorry I forgot to thank you for taking the time to clarify things for me. I appreciate it

1 Like