solidjs / solid-playground

Quickly discover what the solid compiler will generate from your JSX template
https://playground.solidjs.com
MIT License
193 stars 62 forks source link

Question: Is there a store-like type of memo? If not, what's a better workaround? #164

Closed Daniel-Khodabakhsh closed 6 months ago

Daniel-Khodabakhsh commented 6 months ago

Say there is a store named mousePosition which contains an adjusted version of the mouse location which gets updates on the mousemove event.

My goal is to create a memo which has a discrete version of the position such as the following:

function normaliseAxis(axis: number): number {
  return Math.ceil(axis / 100);
}

const normalisedPosition = createMemo(() => ({
  x: normaliseAxis(mousePosition.x),
  y: normaliseAxis(mousePosition.y)
}));

Here, the memo makes all of its downstream objects react on every mousemove event because the memo is an object whose reference gets recreated, similar to a signal.

Question 1

Is there a store-like version of a memo which automatically memoises each field of an object such that it won't make downstream objects react unless there is a change in a value?

Question 2

If there is no such structure as asked above, which of the following work-arounds would be a better choice and why?

Choice 1

const normalisedPositionX = createMemo(() => normaliseAxis(mousePosition.x));
const normalisedPositionY = createMemo(() => normaliseAxis(mousePosition.y));

Choice 2

const normalisedPosition = createMemo(
  (previousPosition) => {
    const newPosition = {
      x: normaliseAxis(mousePosition.x),
      y: normaliseAxis(mousePosition.y)
    };

    if (newPosition.x === previousPosition.x && newPosition.y === previousPosition.y)
      return previousPosition;

    return newPosition;
  },
  {x: 0, y: 0}
);

Here is a playground link illustrating the question: https://playground.solidjs.com/anonymous/a847c828-eab8-4ccb-a9af-789afdf45f18

Daniel-Khodabakhsh commented 6 months ago

Sorry posted it in the wrong repo.