Home > Web Front-end > JS Tutorial > React : Keeping Components Pure

React : Keeping Components Pure

DDD
Release: 2024-10-22 06:22:03
Original
683 people have browsed it

React : Keeping Components Pure

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;
}

Copy after login

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>
  );
}

Copy after login

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.

The above is the detailed content of React : Keeping Components Pure. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template