← react hacks / react / prop-passing-with-spread-operator.md

Prop Passing with Spread Operator in React

Discover the power of the spread operator in React. Learn how to leverage it for seamless prop passing, enhancing your React development experience.

In React, passing props can become cumbersome when the component receives many props. The ... (spread operator) can be used to effectively handle this.

const ComponentA = (props) => {
  return <ComponentB {...props} />
}

In ComponentA, we are spreading out props object and passing it to ComponentB. All properties of props are passed as separate props.

This not only makes the code cleaner but also reduces the chance of missing any prop while passing.

Be aware, the spread operator passes all properties, even those not expected by ComponentB. This can lead to unexpected behavior. So use it wisely!

const ComponentA = ({ prop1, prop2, ...rest }) => {
  return <ComponentB prop1={prop1} {...rest} />
}

In this example, prop1 is passed separately, while the rest are spread out. This allows for better control over what props are passed.

Remember, the spread operator can greatly simplify your code and make prop passing more manageable. But always be cautious of its unintended side effects.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?