Is it possible to partially apply a React component?

Viewed 906

Say I have a <Button> component which takes two properties: text and id e.g.,

<Button text="delete" id="123"/>

Now say I have a list of user ids: [101, 102, 103, …]

Would it be possible to partially apply <Button>? e.g.,

ids.map(<Button text="delete" id={__}>)

Where __ is just a placeholder waiting to be replaced with the current id.

If it was possible, would partially applying a React component have any adverse effect on the React Reconciliation Algorithm?

2 Answers

You could use two ways

one, which is not really a partial

ids.map((id)=><Button text="delete" id={id} />)

and the partial one which is really extracting the function above and using it

const PartialDeleteButton = (id) => <Button text="delete" id={id} />

ids.map(PartialDeleteButton)

which you could also use as

<PartialDeleteButton id={5} />

i cannot see how these would affect the reconciliation algorithm

There is no partial render of a component in React.

A component watches on state and props. Whenever you change either one, it will refresh the component. So if you change id dynamically, it will re-render the component.

However that would be 1 extra re-render.

You can however choose to write functions to prevent that like

  • React.memo: For latest react
  • shouldComponentUpdate: For older version.

Following is a demo for React.memo:

What to look in fiddle, notice I have added a setTimeout that updates data and it will call the render of ToDoApp but since components are memoised, it will not be called

function Button({id, value}) {
    const onClick = () => {
    console.log(`${id} - ${value}`)
  }
  console.log(`Rendering Btn ${value}`)
    return (<button id={id || '__'} onClick={onClick}>{ value }</button>);
}

const MyButton = React.memo(
    Button,
  (prevProps, nextProps) => {
    return prevProps.value === nextProps.value
  }
)

Note: Since you will stop rendering of a component, you will not get updated props in it.

Related