React Native — Anti pattern while calling Component (ERROR, Solution & analysis)
Use React way instead of Functional way of calling a Component.
Basically, there are two ways of calling a Component inside your JSX code. They are:
Suppose you have a component named as “SoccerCard”. You can reuse this “SoccerCard” component in different screens in your React Native App.
Let’s see the “SoccerCard” component looks like below:
Now, there is a screen Home.js from where you will access that “SoccerCard” component.
Functional Way
Now we will use functional way of calling a React Component SoccerCardfrom Home.js screen.
React way
Now we will use React way of calling a React Component “SoccerCard” from Home.js screen.
Functional or React way?
So now it is very important to know, which one should we use? Each one has its own pros and cons.
Let me explain the difference between the two ways Functional & React way.
Functional Way
The first way is to call the “SoccerCard” component as a function and pass the data as an argument.
This way is simple and straightforward, but it has some drawbacks:
React Way
The second way is to use the “SoccerCard” component as a JSX element and pass the data as a prop.
This way is more consistent with the React best practices and has some benefits:
领英推荐
? Now you can decide which one you should use. ?
Still confused? Let’s understand why you must have to use React Way instead of Functional way.
Functional way creates silent ERROR! ??♂?
Let’s once again see the code of functional way of calling a component “SoccerCard” from your “Home.js” screen.
When you will run your App & load screen “Home.js” using the above functional way of calling component “SoccerCard”, you will see a silent ERROR like below in your metro:
Analysis the ERROR
So, why the ERROR occurred?
Answer: ERROR occurred as functional way of calling a component always creates a custom hook. Which means React understand that you created a custom hook “SoccerCard” & now you are calling that hook.
Ok, I got it that React understood that I created Custom hook “SoccerCard” & then called the Custom hook! But why that error like “React has detected a change in the order of Hooks called by Home” printed in metro!
This is because I called the custom Hook “SoccerCard” from JSX code & it violates the rule of Hooks of React.
Functions whose names start with use are called Hooks in React.
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component:
It’s not supported to call Hooks (functions starting with use) in any other cases, for example:
Solution
The solution is just always following the best practices given by React & React Native team. For this one use React wayinstead of Functional way:
??Backend Developer | PHP | ReacJS | NodeJS | MySQL | Database Optimize??
8 个月Thank for sharing