Why does component remount every state update?
20:01 10 May 2021

EDIT:

I made some stupid mistakes within my code prior to asking this question. I realise now that this question likely will not serve as useful to anyone as what I am saying is actually in itself misleading. Apologies and thank you to those that replied.


I am currently learning React Native and have come across some unintuitive behaviour. As far as I am aware, the useEffect hook can be used in such a way to determine the life-cycle of a component (i.e. when it mounts and dismounts). When I update the state within a component (in this case 'ComponentX'), the entire component seems to remount. I did not think that this was the intended behaviour. If someone could tell me if it is so - or what I am doing wrong that is causing this to happen - that would be very helpful! Thanks.

Expected behaviour: Component does not unmount and remount.

Actual behaviour: Component remounts on every state change.

import React, { useEffect, useState } from "react";
import { Text, TouchableHighlight, View } from "react-native";

export default function App() {
  return (
    
  );
}

const ComponentX = () => {
  const [componentState, setComponentState] = useState(0);

  useEffect(() => {
    console.log("mounted");
    return () => console.log("unmounted");
  }, []);

  return (
    
       {
          setComponentState(componentState + 1);
        }}
      >
        Update State
      
      {componentState}
    
  );
};

javascript reactjs react-native use-state