0

So I have this class :

class Dimension {
  @observable name

  @observable label

  @observable active

  @observable color

  @observable data = []
}

Now I have a store:

class MyStore {
  @observable dimensions = []

  constructor() {
    /** some stuff to fill dimensions **/
  }
}

const MyStoreContext = createContext(new MyStore());

export default MyStoreContext;

After an API call to the server I get some data and create Dimension objects and put them in the array.

Now I have two components where I use these dimensions, one where I need the data and one where I don't.

Problem is I have a button that recalculates the data - without changing anything except that, but because I call dimensions as so :

const component = observer(() => {
  const store = useContext(MyStoreContext);

  const dimensions = store.dimensions;

  return (
    dimensions.map(dimension => <span style={{color: dimension.color}}> dimension.name </span>)
  )
}

const component2 = observer(() => {
  const store = useContext(MyStoreContext);

  const dimensions = store.dimensions;

  return (
    /** Something with dimension.data **/
  )
}

In both places, when there is a change of the data in dimensions (even though I don't use it) the component still re renders.

I wonder how can I use dimensions in both places but to make sure only what is necessary gets rendered.

Must I pass the dimensions as props to the component?

user3467713
  • 131
  • 1
  • 11

1 Answers1

0

I've tried to reproduce your behaviour but could not do it. Everything works as expected, if you change only data part of dimension then only components which use this data field will be rerendered.

https://codesandbox.io/s/httpsstackoverflowcomquestions63157530-p6fcs?file=/src/App.js

Try to compare your code with mine, maybe there is some differences?

Danila
  • 15,606
  • 2
  • 35
  • 67