In React, is it good to pass all the details from the parent to the child component?

Say I have a parent component and one child component.

props has ten keys, but only three are needed for a child.

What is the best way to pass details to a child component?

 class Parent extends Component { render() { { /*pass all the ten keys into child*/ } <Child {...this.props} /> } } 

or

 class Parent extends Component { render() { { /*pass only the needed keys into child*/ } <Child key1={key1} key2={key2} key3={key3}/> } } 
+10
source share
2 answers

Transferring all the details is not a good idea at all. More props mean more things that can lead to unnecessary re-rendering of a child component. However, it is convenient to use the distribution operator on a subset of these details. For example, the parent component can receive many details, but does not use most of them and instead passes all but one or two to the child component. Consider this example using something like redux-form:

 export function Form({ handleSubmit, ...rest }) { return ( <form onSubmit={handleSubmit}> <Field name="name" component={FormInput} /> <SaveButton {...rest} /> </form> ); } 

The external form component only cares about the submit function. Other details indicating whether the form is dirty, valid, etc. Will be used by <SaveButton /> to determine whether the button should be disabled.

This is convenient because we do not need to declare the details for a component that does not use them. We just pass them on. But, as stated earlier, use this template with caution, making sure that you know what details you are actually transferring, because it can cause performance problems or even side effects.

In fact, I would say that if you often go through the details through the hierarchy, you probably have a design problem and you should use your redux store more efficiently.

+15
source

No, this is usually a bad idea. In general, it’s better to just pass the component what it needs:

  1. Less props are required to determine if a component has changed.
  2. It’s easier to understand what a component does.
  3. You can statically analyze what a component needs, and refactoring becomes easier

You can use the lodash _.pick function:

<Child {...(_.pick(this.props, ['key1', 'key2', ...]))} />

+3
source

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


All Articles