Home > Net >  Component still rendering after unmount?
Component still rendering after unmount?

Time:02-10

I have a component that look like this where I clear the state on unmount, however this is causing me problems. After the component has unmounted, the state is successfully cleared but then I get an error saying undefined is not an object (evaluating someState.first). I don't understand why this is still being rendered after unmount, from what I understand after a component has been unmounted the component shouldn't render anymore?

const SomeComponent = () => {
  const [someState, setSomeState] = ({
    first: 'John',
    last: 'Doe'
  });

  useEffect(()=>{
    someFunction();
    return () => {setSomeState()}
  }, []);

  const someFunction = () => {
    setSomeState({
      first: 'John',
      last: 'Doe',
    });
  }

  return (
    <View>
      <Text>{someState.first   ' '   someState.last}</Text>
    </View>
  )
}

CodePudding user response:

someState seems to be undefined in the beginnning. Initialize it :

  const [someState, setSomeState] = ({  first: '',
      last: '',
});

OR

Put a check in your JSX:

 return (
    <View>
      {someState && <Text>{someState.first   ' '   someState.last}</Text>}
    </View>
  )

CodePudding user response:

What are you doing for unmounting the component? In react native if you are using stack navigation, components will not be unmounted until you press back or remove them from the stack. Also please make sure to check your render and change it like this:

  return (
    <View>
      {someState && <Text>{someState.first   ' '   someState.last}</Text>}
    </View>
  • Related