1
votes

I'm using useState to set text from TextInput, and I'm using a useEffect to overwrite the behavior from the back button.

const [text, setText] = useState("");

  <TextInput
    onChangeText={text => setText(text)}
    defaultValue={text}
  /> 

  const printVal() {
    console.log("text is " + text);
  }

 useEffect(() => {
    navigation.setOptions({
      headerLeft: () => (
        <HeaderBackButton onPress={() => printVal()} />
      )
    });
  });

This always results in the text logged being the initial value of useState. If I don't use useEffect it works, but I don't want to set navigation option with every change. Can I get the current value from useState in my useEffect, or is another solution needed?

1

1 Answers

0
votes

You forgot to add dependencies as 2nd parameter to useEffect. you can add an empty array if you want your function to be called only 1 time when component loads, or for this example you should add text as dependecy because useEffect depends on this value

 useEffect(() => {
    navigation.setOptions({
      headerLeft: () => (
        <HeaderBackButton onPress={() => printVal()} />
      )
    });
  }, [text]);  //<- empty array here