Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Created August 27, 2023 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akiyamka/b80b9f39229584f3c921abc81109e71f to your computer and use it in GitHub Desktop.
Save Akiyamka/b80b9f39229584f3c921abc81109e71f to your computer and use it in GitHub Desktop.

Usage

In react hooks - for reduce memory consumption

import emptyArr from 'dummyArray';

function myEffect() {
  useEffect(() => {
    // On mount logic
  }, emptyArr);
} 

In props for avoid unnecessary rerenders

import emptyArr from 'dummyArray';

function MyComponent({ list = emptyArr }) {
  return <ul>{list.map(l => <li>{l.text}</li>)}
}

or

import emptyArr from 'dummyArray';

function OtherComponent() {
  const data = useData();
  return <OtherComponent list={data?.list ?? dummyArray} />
}
class MutationError extends Error {
message = 'Attempt to mutate empty dummy array';
}
class DummyArr extends Array {
get length() {
return 0;
}
set length(v) {
if (v !== 0) throw new MutationError();
}
reverse() {
return this;
}
sort() {
return this;
}
pop() {
return undefined;
}
shift() {
return undefined;
}
push() {
throw new MutationError();
}
unshift() {
throw new MutationError();
}
splice() {
throw new MutationError();
}
}
export default Object.freeze(new DummyArr());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment