1

so I've started using the law of Demeter recently(heard about it a month ago) and I am currently also learning react.

But let's take this component

function CatImages(props) {
    return props.data.imgSrc.map((cat, index) => (
        <img src={cat} alt="Cat" key={index} />
    ));
}

Where you have a data object that is passed as prop in the component

myData = {
    imgSrc: ['src1', 'src2', 'src3']
}

<CatImages data={myData} />

As far as I understand, imgSrc is a stranger.

Same would happen if you save data in the component state and then access it like this.state.data.imgSrc

One solution would be to pass imgSrc={data.imgSrc} and use it directly as props.imgSrc or save imgSrc in the state directly

Even using a state management system like Redux, will break this law.

I would like to know if the Law of Demeter should be something to worry about when working with objects passed as props or saved in the state so I don't overkill the code.

Thanks

Mihai Marinescu
  • 741
  • 8
  • 22
  • 2
    Does this answer your question? [React props: Should I pass the object or its properties? Does it make much difference?](https://stackoverflow.com/questions/52621169/react-props-should-i-pass-the-object-or-its-properties-does-it-make-much-diffe) – andy mccullough Jan 07 '22 at 12:49
  • 1
    Thanks, didn't know about https://en.wikipedia.org/wiki/Principle_of_least_privilege, but what about saving objects in the state? – Mihai Marinescu Jan 07 '22 at 12:54
  • 1
    saving objects in state is fine, just remember that in order for rerenders etc to work properly, you must treat objects as immutable. – andy mccullough Jan 07 '22 at 13:04
  • 1
    Not the saving is the issue. I want to know if accessing object properties like `this.state.data.prop` automatically breaks the Law of Demeter, because prop seems like a stranger to state. – Mihai Marinescu Jan 07 '22 at 13:08
  • 1
    firstly, I personally wouldn't just 'dump' `data` into state, have your state in a shape that holds only the properties that you care about, so put the likes of `imgSrc` onto state directly, therefore `this.state.imgSrc`, then based on that, im not quite sure there is anything to worry about with `imgSrc` being a 'stranger' to `state` - to me that just sounds like you are going to end up fighting with React to please some arbitrary law – andy mccullough Jan 07 '22 at 13:35

1 Answers1

0

If you only pass the data you need to your CatImages component, it should, as far as I can see, hold true to the Law of Demeter?

function CatImages(props) {
    return props.imgSrcs.map((cat, index) => (
        <img src={cat} alt="Cat" key={index} />
    ));
}
myData = {
    imgSrc: ['src1', 'src2', 'src3']
}

<CatImages imgSrcs={myData.imgSrc} />
andy mccullough
  • 9,070
  • 6
  • 32
  • 55