Skip to content

useQuery is not stable #50

Open
Open
@DanAmador

Description

Good day.

I recently found out that a useQuery used in a hook I was trying to debug kept being triggered even though the objects weren't changing which caused an infinite loop used in a useEffect

export const Object3DTrait = trait({ ref: new Object3D() });
export const SelectableTrait = trait();
export const SelectedTrait = trait();
  const selectedEntities = useQuery(Object3DTrait, SelectableTrait, SelectedTrait);
  const selectedEntityModels = useMemo((): Object3D[] => {
    const selection = selectedEntities
      .map((entity: Entity) => entity.get(Object3DTrait)?.ref)
      .filter(Boolean) as Object3D[];
    return selection;
  }, [selectedEntities]);

I currently found a work around by creating a stable immutable query hook

export function useStableQuery<T extends QueryParameter[]>(...parameters: T): Entity[] {
  const world = useWorld();
  const [entities, setEntities] = useState<Entity[]>(() => [...world.query(...parameters)]);

  useEffect(() => {

    const update = () => {
      const newResults = [...world.query(...parameters)];
      setEntities(newResults);
    };


    update();


    const unsubAdd = world.onAdd(parameters, () => {
      update();
    });

    const unsubRemove = world.onRemove(parameters, () => {
      update();
    });

    return () => {
      unsubAdd();
      unsubRemove();
    };

  }, [world, ...parameters]);

  return entities;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions