R.M. Reza
R.M. Reza

Reputation: 999

React Props: Pass All Objects or Only Properties The Component Needs?

I have a React component that only expects some values, but I've been passing objects to components a lot regardless of whether the properties of those objects are used in the component or not.

Here is the code example I mean where I pass the Post object to the Title component, that means I also pass the comments even though the Title component doesn't need it.

type Post = {
  title: string;
  comments: Comment[];
};

function Title({ post }: { post: Post }) {
  return <h1>{post.title}</h1>;
}

function Post(post: Post) {
  return (
    <div>
      {/* here: */}
      <Title post={post} />

      {/* .... */}
    </div>
  );
}

And here I just passed the title to the Title component.

type Post = {
  title: string;
  comments: Comment[];
};

function Title({ title }: { title: string}) {
  return <h1>{title}</h1>;
}

function Post(post: Post) {
  return (
    <div>
      {/* here: */}
      <Title title={post.title} />

      {/* .... */}
    </div>
  );
}

What I want to ask is which one should I use better?

Upvotes: 3

Views: 1534

Answers (2)

The second option is the better one. With the first option, you are combining to separate things to be dependent on each other. Post-interface does not have to do anything with the Title-component. By combining these, you will make code less maintainable. If the Post -the interface will change, you may end up breaking the Title -component.

React -component props should be treated as any API. You should always emphasize loose coupling where you keep interdependencies at a minimum all the time.

In your case, there is also a third option. You could make the Title component use children -props and give the title content as it is being done with HTML -title -component too:

<Title>My title text</Title>

Upvotes: 1

Mroxlog
Mroxlog

Reputation: 26

It's generally up to personal preference since the results are the same. I prefer the second route you took, as it is more specific. You could also use object destructuring to pull out the title from the object.

type Post = {
  title: string;
  comments: Comment[];
};

function Title({ post }: { post: Post }) {
  const {title} = post
  return <h1>{title}</h1>;
}

function Post(post: Post) {
  return (
    <div>
      {/* here: */}
      <Title post={post} />

      {/* .... */}
    </div>
  );
}

Upvotes: 1

Related Questions