This content originally appeared on DEV Community and was authored by Sonay Kara
Keeping Components Pure
Some JavaScript functions should be pure. Pure functions only perform a calculation and nothing else. By writing your components as pure functions, you can avoid all of the confusing errors and unpredictable behavior as your code base grows. You can make your components easy to manage.
Purity
So how can we create a pure function? And what characteristics should a function have for it to be pure? A pure function should be a function with the following characteristics :
It minds its own business. It does not change any objects or variables that existed before it was called.
Same input, same output. Given the same inputs, a pure function should always return the same result. It should not give different results to the same inputs.
Let's consider a mathematical formula : y = 2x
If x = 2, y = 4. This invariant is always the same result.
If x = 3, y = 6. This invariant is always the same result.
If x = 3, sometimes y will not be 9, –1, or 2.5, depending on some other situation.
If y = 2x and x = 3 then y will always be 6.
If we made this into a JavaScript function :
function getDouble(number) {
return 2 * number;
}
getDouble is a pure function. If you pass it 3, it will return 6. Always.
React is built around this concept. It assumes that each component behaves like a pure function, meaning your React components should always return the same JSX output given the same inputs.
Let's explain a pure compound by giving examples.
function Member({ user }) {
return (
<ol>
<li> register {user} </li>
</ol>
);
}
export default function App() {
return (
<section>
<Member user={2} />
<Member user={4} />
</section>
);
}
It always returns whatever the user parameter is given.like a math formula
You can think of your ingredients like recipes. You know the ingredients, and if you don’t introduce new ingredients during the cooking process, you'll end up with the same dish every time.
Conclusion
A component must be pure, meaning:
It minds its own business. It should not change any objects or variables that existed before rendering.
Same inputs, same output. Given the same inputs, a component should always return the same JSX.
This content originally appeared on DEV Community and was authored by Sonay Kara
Sonay Kara | Sciencx (2024-10-08T20:41:00+00:00) Reatc.js : Keeping Components Pure. Retrieved from https://www.scien.cx/2024/10/08/reatc-js-keeping-components-pure/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.