What are React Components?

React components are the building blocks of React applications. They are independent, reusable bits of code that can be combined to create complex UIs. Components can be defined in JavaScript or TypeScript, and they can be used to render HTML, CSS, and JavaScript.

Benefits of using React components:

  • Reusability: It helps to reduce code duplication and improve maintainability.
  • Scalability: Create complex UIs, which can help to keep the code organized and easy to understand.
  • Testability: It helps to improve the quality of the application.

Example of Functional Components

import HelloWorld from './HelloWorld';

const App = () => {
  return (
    <div>
      <HelloWorld />
    </div>
  );
};

export default App;

Functional Components

import HelloWorld from './HelloWorld';

const App = () => {
  return (
    <div>
      <HelloWorld />
    </div>
  );
};

export default App;

Pure Component

import React from 'react';

class App extends React.PureComponent {
  render() {
    const { points = 0 } = this.props;
    return (
      <div>
        <span>{points}</span>
      </div>
    );
  }
}

export default App;

This component takes a points prop and renders it as a span. It is a pure component because it does not modify any state or props, and it always renders the same output for the same input values.

Here is an example of a non-pure component:

import React from 'react';

class App extends React.Component {
  state = {
    points: 0,
  };

  incrementPoints = () => {
    this.setState({
      points: this.state.points + 1,
    });
  };

  render() {
    const { points } = this.state;
    return (
      <div>
        <span>{points}</span>
        <button onClick={this.incrementPoints}>Increment</button>
      </div>
    );
  }
}

export default App;

This component also takes a points prop, but it also has a state property that stores the current number of points. The incrementPoints function increments the number of points in the state and then re-renders the component. This means that the component will render a different output for the same input values, because the number of points in the state has changed.

Pure components are generally preferred over non-pure components because they are more efficient. When React renders a component, it compares the current props and state to the previous props and state. If they are the same, React will not re-render the component. This can lead to significant performance improvement, especially in large applications with complex components.

Here are some tips for writing pure components:

  • Only access state and props in the render function.
  • Do not modify the state or props in the render function.
  • Avoid using side effects in the render function.

If you follow these tips, you can write pure components that will improve the performance of your React applications.

Join Telegram Join Whatsapp

Leave a Comment