Fail to prevent re-render by React.memo - react-native

I am building a react native app for which has a form page contains a lot of textInput and buttons. Each of fields do not causing performance issue.
However, when they are put together, the application will show js thread frame drops in the Perf Monitor. So I think the page is re-rendering all the components when any of the state is changed.
I tried 2 methods.
Moving components out of the main export function.
Using React.memo.
Unfortunately, both of them are not working. The app still lag and re-render every time for all components.
So I created a simple case for it. You may see the code below.
I would like to only re-render the ChildItem for only the respective state changed. For now, console will log from 1 to 5 for any button clicked. Since the props passed to memo component is not changed, I expect the console will only log 1 respective sentence for specific index when button is pressed.
import React, {useState, memo} from 'react';
import { View, Text, Button } from 'react-native';
const ChildeItem = memo( ({index, value, onPress}) =>{
console.log(`ChildeItem ${index} rendered`);
return(
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1, textAlign: 'center'}}>
{value}
</Text>
<View style={{flex: 1}}>
<Button
onPress={onPress}
title={"+"}
/>
</View>
</View>
)
});
export default function TestScreen({navigation}) {
const [value1, setValue1] = useState(0);
const [value2, setValue2] = useState(0);
const [value3, setValue3] = useState(0);
const [value4, setValue4] = useState(0);
const [value5, setValue5] = useState(0);
return(
<View>
<ChildeItem index={1} value={value1} onPress={()=>{setValue1(value1+1);}} />
<ChildeItem index={2} value={value2} onPress={()=>{setValue2(value2+1);}} />
<ChildeItem index={3} value={value3} onPress={()=>{setValue3(value3+1);}} />
<ChildeItem index={4} value={value4} onPress={()=>{setValue4(value4+1);}} />
<ChildeItem index={5} value={value5} onPress={()=>{setValue5(value5+1);}} />
</View>
)
}
Or I have any misunderstanding for React.memo? Any help will be appreciated. Thanks.

Your index and value props are ok for memoization, but your onPress prop causes re-render because on every render of the TestScreen, your onPress prop functions are re-created, so it's reference changes. You can prevent this by using useCallback hook.
export default function TestScreen({navigation}) {
const [value1, setValue1] = useState(0);
const [value2, setValue2] = useState(0);
const [value3, setValue3] = useState(0);
const [value4, setValue4] = useState(0);
const [value5, setValue5] = useState(0);
// Use useCallback for each function
const onPress1 = useCallback(() => setValue1(value1+1), [value1]);
const onPress2 = useCallback(() => setValue2(value2+1), [value2]);
const onPress3 = useCallback(() => setValue3(value3+1), [value3]);
const onPress4 = useCallback(() => setValue4(value4+1), [value4]);
const onPress5 = useCallback(() => setValue5(value5+1), [value5]);
return(
<View>
<ChildeItem index={1} value={value1} onPress={onPress1} />
<ChildeItem index={2} value={value2} onPress={onPress2} />
<ChildeItem index={3} value={value3} onPress={onPress3} />
<ChildeItem index={4} value={value4} onPress={onPress4} />
<ChildeItem index={5} value={value5} onPress={onPress5} />
</View>
)
}
By using useCallback hook, you're memoizing the onPress functions, so they are re-created only when the relevant value changes.

Related

Dimesnion from React/native not working properly on Android device

I am trying to create an Instagram like reel functionality in react-native app.
I want to display a video element on entire screen available space.
For the purpose of it I am using a FlatList.
This code doesn't work on every device.
'const HomeScreen = ({navigation}) => {
const dataArray=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
const renderItem=({item,index})=>{
return(
<View style={[{height:Dimesnions.get('window').height-bottomtabBarHeight,borderBottomColor:'black'},]}>
<Text>{item}</Text>
</View>
)
}
return (
<SafeAreaView style={styles.container}>
<StatusBar />
<FlatList
data={dataArray}
renderItem={renderItem}
pagingEnabled
decelerationRate={'fast'}
/>
</SafeAreaView>
)
}
export default HomeScreen
const styles = StyleSheet.create({
container:{
flex:1,
}
})`
work for me
import dimansion from react native
const {height,width} = dimansion.get('window')
const Myfun=()=>{
return(
<View style={{flex:1}}>
<View style={{height:height}}></View>
</View>
)
}
actually what you need to do is make a state variable and assign dimension's value in it and then in useEffect make a listener which would be triggered every time your device rotates or dimensions of device gets changed
example below:
const [dim, setDim] = useState(Dimensions.get('screen');
useEffect(() => {
const subscription = Dimensions.addEventListener(
'change',
({ screen}) => {
setDim({ screen});
},
);
return () => subscription?.remove(); });
you can use dim.height for height and dim.width for width in your desired component
PS. I have made a complete and comprehensive tutorials regarding Dimensions API if you want to check it out then link is below(Tutorial is in Urdu/Hindi)
https://www.youtube.com/watch?v=mISuyh_8-Cs&t=605s&ab_channel=LearnByDill
I think it is because of typo which you used Dimesnions instead of Dimensions. You can get height or width of device as below:
const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;

react native textinput lost focus after 1 char type

I have this problem with ios but not with android. It only disturb the add task input the task edit and the list name edit. The input addList(It's the one with "What to do?" on the draw) in the header works fine.
UI drawing
Achitecture of components
I console log my component and I can see it rerender everytime I add a letter in the input field.
I checked on google and follow this:(can we link other website here?) https://www.codegrepper.com/code-examples/javascript/react+native+textinput+lost+focus+after+charter+type
Tried the the first solution with onBlurr and onFocus.
I tried to make a TextInput component for add task.
I even try with my component addList but it didn't solve the problem.
Anyone have faced this problem before? Is there anyway to by pass this?
My code without the import/style look like this:
const TaskList: FunctionComponent<TasksListProps> = ({
addTask,
deleteTask,
toggleTask,
editTaskName,
...props
}) => {
console.log('props', props);
const [nameOfTask, setNameOfTask] = useState('');
console.log('name', nameOfTask);
const textHandler = (enteredName: string) => {
setNameOfTask(enteredName);
};
const handleSubmitTask = () => {
if (nameOfTask === '') {
return;
}
addTask(props.listId, nameOfTask);
setNameOfTask('');
};
return (
<View style={styles.tasksListContainer}>
{props.tasks.map(task => (
<SingleTask
key={task.id}
task={task}
listId={props.listId}
deleteTask={deleteTask}
toggleTask={toggleTask}
editTaskName={editTaskName}
/>
))}
<View style={styles.taskInputContainer}>
<TextInput
style={styles.tasksTextInput}
value={nameOfTask}
onChangeText={textHandler}
placeholder="Write a task to do"
/>
<TouchableOpacity onPress={handleSubmitTask}>
<Image source={require('./Img/add-button.png')} />
</TouchableOpacity>
</View>
</View>
);
};
You can create a HOC and wrap your screen width DismissKeyboard
import { Keyboard } from 'react-native';
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
That because Re render.
Try to make the input with the main component of the page to test it.
Then check where the error with re-render

Entering input causes modal reloading automatically

In my React Native 0.62.3 app, a modal is used to collect user input. Here is the view code:
import { Modal, View, TextInput, Button } from 'react-native';
const [price, setPrice] = useState(0);
const [shippingCost, setShippingCost] = useState(0);
const ReturnModal = () => {
if (isModalVisible) {
return (
<View style={styles.modalContainer}>
<Modal visible={isModalVisible}
animationType = {"slide"}
transparent={false}
onBackdropPress={() => setModalVisible(false)}>
<View style={styles.modal}>
<Text>Enter Price</Text>
<TextInput keyboardType={'number-pad'} onChange={priceChange} value={price} autoFocus={true} placeholder={'Price'} />
<TextInput keyboardType={'number-pad'} onChange={shChange} value={shippingCost} placeholder={'SnH'} />
<View style={{flexDirection:"row"}}>
<Button title="Cancel" style={{bordered:true, backgroundColor:'red'}} onPress={modalCancel} />
<Button title="OK" style={{bordered:true, backgroundColor:'white'}} onPress={modalOk} />
</View>
</View>
</Modal>
</View>
)
} else {
return (null);
}
}
return (
<Container style={styles.container}>
//.....view code
<ReturnModal />
</Container>
)
Here is 2 functions to reset state of price and shippingCost:
const priceChange = (value) => {
if (parseFloat(value)>0) {
setPrice(Math.ceil(parseFloat(value)));
}
};
const shChange = (value) => {
if (parseFloat(value)>=0) {
setShippingCost(Math.ceil(parseFloat(value)));
}
};
The problem is that whenever entering in the price field with keystroke, the modal reloads/resets itself automatically. Tried onChangeText in TextInput and it has the same problem.
It seems like you're declaring your hooks outside your component. Try putting them inside your ReturnModal function instead, like this:
const ReturnModal = () => {
const [price, setPrice] = useState(0);
const [shippingCost, setShippingCost] = useState(0);
...
Documentation reference: Using the State Hook.
Also, I would strongly recommend using the React Hooks ESLint Plugin (among others) to detect issues with your hooks. Here is a guide on how to add this to your React Native project: Add Eslint Support to your React Native Project + React Hooks Rules.
Instead of using animationType = {"slide"} try using animatonType : 'none'

OnPress change the style of component from loop- React Native with hooks

So I am pretty new in react native, I am trying to develop a quiz game, where users will be given Set of answers. I want to select change the color of the component when it is pressed by the user, kind of toggle it. So far I came up with useState solution, but unfortunately cannot figure out how to exclude the change of color, I guess I need to follow indexing or something, can anyone please make me understand the process with the solution.
export const QuizScreen = ({ navigation,route }) => {
const [quizArray, setQuizArray] = React.useState([])
const [rightAnswer, setRightAnswer]= React.useState(false)
const [selectBtn, setSelectBtn] = React.useState("#fff")
return(
<View>
{quizArray[qno].answer.map(r=>
<TouchableHighlight style={[styles.listItem, {backgroundColor:selectBtn}]}
onPress={()=>{
setRightAnswer(r.rightAnswer)
setSelectBtn("#DDDDDD") //so this changes logically all the component from the list
}}
activeOpacity={0.6} underlayColor="#DDDDDD"
>
<Text>{r.option}</Text>
</TouchableHighlight>
)}
</View>
I need to know how do i implement the background change for only one and kinda make it toggle everytime user select or deselect. Thank you
You were right about using an index for determining the clicked list item.
You can change the color by storing the index of the selected item using selectBtn state and then using that state set the backgroundColor accordingly.
Here is how you can do it:
export const QuizScreen = ({ navigation, route }) => {
const [quizArray, setQuizArray] = React.useState([]);
const [rightAnswer, setRightAnswer] = React.useState(false);
const [selectBtn, setSelectBtn] = React.useState(null);
return (
<View>
{quizArray[qno].answer.map((r, index) => (
<TouchableHighlight
style={[
styles.listItem,
{ backgroundColor: selectBtn === index ? '#dddddd' : '#fff' },
]}
onPress={() => {
setRightAnswer(r.rightAnswer);
setSelectBtn(index);
}}
activeOpacity={0.6}
underlayColor="#DDDDDD">
<Text>{r.option}</Text>
</TouchableHighlight>
))}
</View>
);
};
Here is the working example: Expo Snack
2

One form, but different state

I'm moving now from other technologies to React Native and I have a problem. I have one presentational component which is <TaskInput />.
const TaskInput = (props: ITaskInputProps) => {
return (
<View style={styles.container} >
<Text style={styles.title}>{props.title}</Text>
<TextInput
style={styles.input}
multiline
scrollEnabled={false}
/>
</View>
)
}
ParentComponent over TaskInput
import React from 'react';
import { View } from 'react-native';
import styles from './styles';
import TaskInputContainer from '../task-input';
interface ITaskConfigurationProps {
title: string,
isInputForm?: boolean,
isRequired?: boolean,
}
const TaskConfiguration = (props: ITaskConfigurationProps) => {
return (
<View style={(props.isRequired) ? [styles.container, {backgroundColor: '#f25e5e'}] : styles.container}>
{ props.isInputForm && <TaskInputContainer title={props.title} /> }
</View>
);
}
export default TaskConfiguration;
const TaskScreen = (props: ITaskScreenProps) => {
return (
<View style={styles.container}>
<SectionTitle title={'Task Settings'} />
<ScrollView contentContainerStyle={styles.configurations}>
<TaskConfiguration title={"What you need to do?"} isInputForm={true} isRequired={true} />
<TaskConfiguration title={"Description"} isInputForm={true} />
<TaskConfiguration title={"Deadline"} />
<TaskConfiguration title={"Priority"} />
</ScrollView>
<Button isDone={true} navigation={props.navigation} />
</View>
)
}
TaskInput component takes one prop which is title and it will be in two places on my screen. One component will be called "Enter main task", another one is "Description". But this component will accept different states like currentMainTextInput and currentDescriptionTextInput. This is my idea of re-usable component TextInput, but I can't do what I want because if I set type in one input - other input will re-render with first input (both of them are one presentational component).
I want to use this dumb component in any place of my app. I don't want to create a new identical component and duplicate code, How can I do that? (P.S. I was thinking about "redux or class/hooks", but what should I use...)