In my React Native app, i am rendering an array and i have toggle buttons set in that page. If i change any one item, the array gets changed and the component rerenders which result in flickering of the component. How can i just change the item that's needed to be changed and stop the flickering.
Here's my current component:
const Notifications = () => {
const dispatch = useDispatch();
const { t } = useTranslation('setting');
const notificationStatus = useSelector(getNotificationModeSelector);
const setNotificationStatus = useCallback(
(value: any) => dispatch(notificationsActions.setNotifications(value)),
[dispatch],
);
const getNotificationStatus = useCallback(
() => dispatch(notificationsActions.getNotifications()),
[dispatch],
);
const onToggleNotification = useCallback(async (item) => {
var changeParam = notificationStatus.map(obj =>
obj.id === item.id ? { ...obj, enabled: obj.enabled ==='1' ? '0' : '1' } : obj
);
setNotificationStatus(changeParam);
}, [notificationStatus, setNotificationStatus]);
useEffect(() => {
getNotificationStatus();
}, []);
console.log('Notifications Page',notificationStatus );
return (
<DesktopContainer>
<Container>
{notificationStatus.length !== 0 && notificationStatus.map((item)=>{
return(
<Wrapper key={Math. floor(Math. random() * 100)}>
<Title>{item.name}</Title>
<Switch
onColor={styles.SWITCH_COLOR}
offColor={styles.MEDIUM_GRAY}
isOn={item.enabled === '1' ? true : false}
size={
Dimensions.get('screen').width > styles.MIN_TABLET_WIDTH
? 'large'
: 'medium'
}
onToggle={()=>onToggleNotification(item)}
/>
</Wrapper>
)
})
}
</Container>
</DesktopContainer>
);
};
export default memo(Notifications);
CodePudding user response:
The issue is on this line:
<Wrapper key={Math. floor(Math. random() * 100)}>
Your key
should always be a fixed value. If your notificationStatus
item has a unique ID, that's ideal. React optimizes its render cycle by using these keys; that's what allows it to only change what it needs. Since all of your mapped components have new keys on each render, React re-renders them all.
See the "Picking a Key" section of this tutorial for more. https://reactjs.org/tutorial/tutorial.html