If you liked the article, you can buy a coffee to support Buy me coffee
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
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.
Top comments (1)
This aligns well with the idea of "container" and "presentation" components. Variables, data, and externals have to connect at some point, so isolating data access, side effects, and other "impurities" to container elements can be helpful.
The more you can isolate the presentation of your code into pure functional components, the easier it is to ensure the expected output...and to write tests.