Setting this to true
means that the {propName}
prop of the component should be treated as a stable, dependency-free value - i.e. it only references values that will not change between renders (such as refs and setState functions), or in another way to say, shall be safe to pass into the useCallback
hook without any specifying any dependencies.
<Button onPressIsStable onPress={() => Alert.alert('Pressed')} /
This is a performance optimization to prevent unnecessary re-renders of the component, and should only be used when the propName
function is guaranteed to be stable.
For example, to prevent unnecessary re-renders of components that use the onValueChange
prop, we would wrap the onValueChange
function with useCallback
. In many cases, the onValueChange
function does not depend on any props or state, and can be safely wrapped with useCallback
without any dependencies, such as:
<MySwitch
value={state.myValue}
onValueChange={useCallback(
(myValue: boolean) =>
setState((s) => ({
...s,
myValue,
})),
[],
)}
/>
However, this has some drawbacks:
- The code is longer and less convenient to write.
- TypeScript will not be able to infer the parameter type of the
onValueChange
function, and you will need to specify the type manually. - If the component is rendered conditionally, you will not be able to use the
useCallback
hook inside the JSX expression, and will need to move the function definition of theonValueChange
handler function to the top of the component (such asconst handleMyValueChange = useCallback(...)
). Sometimes, this can make the code harder to read and maintain since thehandleMyValueChange
function is not close to where it is used.
By using the onValueChangeIsStable
prop, you can avoid these drawbacks of using useCallback
to wrap the onValueChange
function without dependencies to prevent unnecessary re-renders of the component, as the component will simply ignore the onValueChange
prop when comparing props for re-renders:
<MySwitch
value={state.myValue}
onValueChangeIsStable
onValueChange={(myValue) =>
setState((s) => ({
...s,
myValue,
}))
}
/>