0

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>
  )
}
Ken
  • 1,155
  • 2
  • 19
  • 36
  • Just... don't clear the component-local state at unmount? I don't see why you should do that anyway. – AKX Feb 09 '22 at 19:28
  • I was looking at [this](https://stackoverflow.com/a/65007703/11502399) solution from another StackOverflow post since I was having issues with the `React useEffect causing: Can't perform a React state update on an unmounted component` error and clearing the state did fix this problem – Ken Feb 09 '22 at 19:30
  • 1
    What's your original issue, anyway? If you have an effect whose callback _happens_ to finish after the component has unmounted, it's generally a non-issue. – AKX Feb 09 '22 at 19:38
  • Alright thanks, I guess I can ignore the warning then – Ken Feb 09 '22 at 19:42
  • 1
    You can, yes - you can also use something like [react-use's `useMountedState()`](https://github.com/streamich/react-use/blob/master/src/useMountedState.ts) to avoid the warning if it bothers you. – AKX Feb 09 '22 at 20:16

2 Answers2

0

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>
  )

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Sorry, thanks but I still run into the error when I initialize someState (I have edited my code in the question above) – Ken Feb 09 '22 at 19:33
  • 1
    setting state inside the return is not useful because component is going to be destroyed anyways. It cannot be brought back with that state value. As mentioned in comments, you should remove it – Tushar Shahi Feb 09 '22 at 19:39
0

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>