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

114
Vistas
react native state is updated but functions still using the initial state set at the time of mounting

In my react native functional component, the state gets updated but when I want to use this state inside a function (for e.g, to send data to API), it uses the initial state only.

imports...

const Component = ({ navigation }) => {
  const [ids, setIds] = useState([1,2]);

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => <HeaderRight 
        onPress={() =>
          console.log(ids); // this logs initial state, i.e, [1,2]
          updateIdsToServerViaAPI(); // and therefore I'm unable to update ids using this method
        }
      />
    });
  }, [navigation]);

  const updateIdsToServerViaAPI = async () => {} // function that takes updated ids from state.

  const onPress = async () => {
    const newIds = [...ids, 3, 4];
    setIds(newIds);
  }

  const onPressInsideComp = () => {
    console.log(ids);
    // here updated ids gets logged.
  }

  return (
    <View>
      <Button onPress={onPress} />
      {ids.map(id => (
        <Text key={id}>{id}</Text> {\* Here you will see 4 texts after pressing button, that means state gets updated*\}
      )}
      <Button onPress={onPressInsideComp} />
    </View>
  );
}

Seems like this issue happens only when functions are called inside useLayoutEffect or useEffect but when I call onPressInsideComp from the button inside the component, it logs properly!

I am badly stuck on this weird issue !!

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

0

You have only provided the navigation prop in the dependency array of your useLayoutEffect wrapper, thus the function is not recreated if the ids state changes.

You might want to create a different function, wrapped inside a useCallback which gets the ids state as a dependency and provide this function in your useLayoutEffect.

const doSomething = useCallback(() => {
    console.log(ids); 
    updateIdsToServerViaAPI();
}, [ids])

useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => <HeaderRight 
        onPress={() =>
          doSomething(ids)
        }
      />
    });
  }, [navigation, ids, doSomething]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

In your code, the console.log(ids) is resolved at the moment of the function definition, and not at execution time, so it takes the reference you get in the definition const [ids, setIds} = useState([1,2]).

Maybe just try to get your ids with a function of state instead of using a variable that has been defined before:

  const [ids, setIds] = useState([1,2]);
  const get_ids = () => this.state.ids;
  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => <HeaderRight 
        onPress={() =>
          console.log(get_ids());
          updateIdsToServerViaAPI();
        }
      />
    });
  }, [navigation]);
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