I have React Native project. I am new to React. I was told not to put functions in the jsx as it's bad practice. Looking for guidance to keep component clean
// App.js
export const App = () => {
// other things
return (
<CustomButton onButtonPress={()=> someFunction} />
)
}
Then my custom component that I am in question. Should I create a functions which will included the prop or do I use the prop directly in the jsx
export const CustomButton = (props) => {
<Button
onPress={() => props.onButtonPress(item.socketId)}>
Decline
</Button>
or
export const CustomButton = (props) => {
const handleDisconnect = (socketId) => {
props.onButtonPress(socketId)
}
<Button
onPress={() => handleDisconnect(item.socketId)}>
Decline
</Button>
CodePudding user response:
Long story short. React use function component, if you not use memo, your function will be create again and take some memory and time. Also arrow function will recreate too.
import React, { memo, useCallback } from "react";
import { Text, Button } from "react-native";
const ClearCustomButtom = memo(({ onPress, title }) => (
<Button onPress={onPress}>
<Text>{title}</Text>
</Button>
));
const ExtraCustomButtom = memo(({ onPress, title, socketId }) => {
const handlePress = () => {
console.log("Some extra action");
onPress(socketId);
};
return (
<Button onPress={handlePress}>
<Text>{title}</Text>
</Button>
);
});
const RequestCustomButtom = memo(({ url, title }) => {
const handlePress = () => {
//send request on server
};
return (
<Button onPress={handlePress}>
<Text>{title}</Text>
</Button>
);
});
export default function App() {
//UseCallback create point for put in button props, not function but point. Without useCallback component will rerender every time.
const handlePressClearDecline = useCallback(() => {}, []);
const handlePressExtraDecline = useCallback((socketId) => {
console.log(socketId);
}, []);
return (
<>
<ClearCustomButtom
title="ClearCustomButton"
onPress={handlePressClearDecline}
/>
<ExtraCustomButtom
title="ExtraCustomButton"
onPress={handlePressExtraDecline}
socketId="777"
/>
<RequestCustomButtom title="Send request" />
</>
);
}
This example of most common case in react-native, how to write pressable component.