📜 ⬆️ ⬇️

Functional components

As the saying goes, a letter came to the editor: "Could you explain in detail ..." I answer publicly to whom it is necessary, and the application can be felt here .


First there were components on the classes:


class Square extends React.Component { constructor() { super() this.state = { value: null, } } render() { const { value, onClick } = this.props return ( <button className="square" onClick={onClick}> {value} </button> ) } } 

Then came the functional components:


 const Square = ({ value, onClick }) => {( <button className="square" onClick={onClick}> {value} </button> )} 

What is the difference? We throw out: class declaration, constructor (), render (), const for reps, props, this. The state of the component also disappeared - we get stateless functional components.


How to continue to live without a local state: 1) or use functional components only where there is no need to store the state; 2) or transfer the entire state to the redux stor (as the only source of truth). Local component states are an additional level of abstraction that requires maintenance. What for?


It is also desirable to overcome connection fear — not to drag all properties through parent components, but to use connect () for child components as properties are used.


Understood, and how to apply PureComponent to functional components? The Higher-Order Components come to the rescue:


 // utils.js import React from 'react' export const pureComponent = (fn) => { class Wrapper extends React.PureComponent { render() { return fn(this.props, this.context) } } //  , ..       , //   -PureComponent;     () // Wrapper.contextTypes = fn.contextTypes Wrapper.displayName = `PureComponent(${fn.name})` return Wrapper } 

Assignment displayName - for beauty in React DevTools. You can read more about contextTypes here .


Usage example:


 import { pureComponent } from 'utils' const Square = ({ value, onClick }) => {( <button className="square" onClick={onClick}> {value} </button> )} export default pureComponent(Square) 

Featured Articles


')

Source: https://habr.com/ru/post/326610/


All Articles