DEV Community

Discussion on: Don't Sacrifice Your Declarative API for One Use Case - A React Pattern for Conditional Hooks

Collapse
 
chrisza4 profile image
Chakrit Likitkhajorn

Hi, and Thanks for writing this.

May I present you an alternative? I would solve this a little bit different.

I would maintain the <Grid /> as it is, create a <RawGrid />

function RawGrid({
  data, page, reload = () => { }
}) {
  // This grid accept the raw data and reload functionality
}

function Grid({ source }) {
  const [data, setData] = useState({ values: [], count: 0 });
  const [page, setPage] = useState(1);

  // fetch data on page change
  useEffect(() => {
    getData();
  }, [page]);

  function getData() {
    // call the `source` prop to load the data
    return source(page).then((results) => {
      setData(results);
    });
  }

  return (
    <RawGrid data={data} page={page} />
  );
}
Enter fullscreen mode Exit fullscreen mode

And then useGrid can be pair with RawGrid.

Compare between this and the one in the article: The difference is simply a single component that can have many way to consume and two components but each of them have specific API.

While I prefer having a lot of components with specific API, I can see pros and cons in both ways. Sometimes single component can be easier to use because everything is there, and sometimes harder to use because it has so many different behavior based on optional parameters.

So I will just leave an alternative solution and call it a day.