Stateless components

The React stateless component (a functional component) is just a pure JavaScript function that takes props as an argument and returns a react element. The following example shows how a stateless component is used by using the arrow function:

import React from 'react';

const HeaderText = (props) => {
return (
<h1>
{props.text}
</h1>
)
}

export default HeaderText;

Now, when you use functions to define a React component, you don't have to use the this keyword. A stateless component defined using a function doesn't have life cycle methods. For example, in the previous HeaderText example, you can see that there is no render() method.

Our HeaderText example component is called a pure component. A component is said to be pure if its return value is consistently the same given the same input values. React has introduced React.memo(), which optimizes the performance of the pure functional components. In the following code, we wrap our component using memo()

import React, { memo } from 'react';

const HeaderText = (props) => {
return (
<h1>
{props.text}
</h1>
)
}

export default memo(HeaderText);

Now, the component is rendered only if the value of the props is changed. The React.memo() phrase also has a second argument, arePropsEqual(), which you can use to customize rendering conditions, but we will not cover that here.

The benefits of the functional classes are that you write less code and they are easier to read and understand. Unit testing is also straightforward with pure components.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.90.141