I am currently creating a React Native app and still am unsure about how to best handle states for my use case.
I use react-native-svg
to create a rather complex figure in the app, which is stored in a component, stays constant and is retrieved in a parent component. This parent component is then regularly rotated and translated on the canvas, but the path of the complex figure does not change. Therefore, and because the calculations are rather heavy, I would like to calculate the SVG path of that figure only on the start of the app, but not whenever I rotate or translate the parent component. Currently, my code structure looks like this:
Figure Component
const Figure = (props) => {
const [path, setPath] = useState({FUNCTION TO CALCULATE THE SVG PATH});
return(
<G>
<Path d={path} />
</G>
)
}
Parent Component
const Parent = (props) => {
return (
<View>
<Svg>
<G transform={ROTATE AND TRANSFORM BASED ON INTERACTION}>
<Figure />
</G>
</Svg>
</View>
)
}
As you can see I am using a state for the path data. My questions now:
- Am I ensuring here that this path is only calculated once on start?
- Is there a more elegant/better way of doing this (e.g. I am not using the setter function at all right now, so I don't feel like this is the best practice)
EDIT:
The function to calculate the path depends on some props I am passing from the parent component.
{FUNCTION TO CALCULATE THE SVG PATH}
will be evaluated every time a component re-renders. – KyleuseEffect(() => {FUNCTION TO CALCULATE THE SVG PATH}, [])
with emtpy attributes to update the state? – Endorsementprops
of the parent – EndorsementsetPath
in theuseEffect
? Then I don't have a result as mentioned by @zerkms. – Endorsementprop
that the function is reliant on? Is it a primitive like a string or number? – Villeinage