Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How to manage the risk of race conditions in useEffects when a component can un-mount at any time, with React?

$
0
0

Using TypeScript 4, React 17 (current versions at the time I'm writing these lines).

Let say I have the following component.

This component is behind a React Navigation conditional stack navigator. This mean that if the user un-connect, the component will be automatically unmounted and the with the whole UI, showing the login screen instead.

This is managed by such code in the app's root navigator:

user ? (<RootStack.Screen name="Home" component={HomeScreen} />) : (<RootStack.Screen name="Login" component={LoginScreen} />)

Here is a component that print on the home screen.

I had some issues in another project and a friend of mine recommended to always put this un-mounting condition when a component un-mount with a risk of race condition.

I have some race conditions issues but adding un-mounting on all the components did not solved it so far.

Is my friend right that I shall continue to put these un-mounting or is it un-needed for such simple and synchronous cases as the following component?

interface Props {    prop1: number}const MyFunctionalComponent: FC<Props> = ({prop1 = 0}: Props) => {    const [stateVariable, setStateVariable] = useState<string>('initial value')    useEffect(() => {        let mounted = true        if (mounted) {          // We are synchronous, no await there.          const newStateVariable: string = stringify(prop1)          setStateVariable(newStateVariable)        }        return (): void => {          mounted = false        }    }, [prop1])    return <Text>{ stateVariable }</Text>}

What do you use and know about this ?

Thanks


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>