npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-use-load

v1.0.0

Published

One simple React hook to manage fetching data

Downloads

8

Readme

react-use-load

— Data loading management in React based on React hooks.

useLoad() is a custom React hook that handles loading and catching errors.

It also have full TypeScript support as it is written in this language.

Example:

import useLoad, { Loading } from 'react-use-load';

const fetchData = fetch('path-to-your-api')
                   .then(r => r.json());

const DataComponent = () => {
  const data = useLoad(fetchData);

  if (data === Loading)
    return <LoadingSpinner />;
  if (data instanceof Error)
    return <ErrorPopup error={data} />;

  return data...; // render your data!
}

Yes, that's it!

I was personally tired of writing useStates and useEffects all the time (as well as writing actions for everything in Redux 😕). Writing such hook was a logical outcome.

I tried to make a hook that returns a single variable, so you control the name of it.

And data === Loading or data instanceof Error can be read so naturaly!

Dependencies

Usually requests have some dependencies. For example, it can be getting user by user id, or getting page data by count & offset.

useLoad() supports dependencies!

Example:

import useLoad from 'react-use-load';

const UserPopup = ({ userId }) => {
  const user = useLoad(() => fetchUser(userId), [ userId ]);

  if (user === Loading)
    return <LoadingSpinner />;
  if (user instanceof Error)
    return <ErrorPopup error={user} />;
  
  return user...; // render user data
}

This way each time when userId is changed, useLoad() will trigger loader and will set user back to Loading.

Basically, you can imagine that useLoad arguments are the same as in useCallback.

Stateful useLoad()

Sometimes we need to edit something that we received. For example, we loaded a user and we are making a cabinet that can change user data.

Now try to imagine how much useEffect and useState you would need to implement this with useLoad(). Two?

const loadedUser = useLoad(fetchUser);
const [user, setUser] = useState(null);
useEffect(() => {
  if (loadedUser !== Loading && !(loadedUser instanceof Error))
    setUser(loadedUser);
}, [ loadedUser ])

Yes, two.

Well, what if I say you that inside useLoad() there is already the state! So by doing this you would just create twice more states and effects.

That's why there is useLoadState():

const [user, setUser] = useLoadState(fetchUser);

That's not all! You now can refresh your user by doing setUser(Loading).

For example:

import { useLoadState, Loading } from 'react-use-load';

const Component = () => {
  const [user, setUser] = useLoadState(fetchUser);

  return (
    <button onClick={() => setUser(Loading)}>
      Refresh
    </button>
  );
}

Component wrapper (Experimental!)

You can see how we repeat those conditions for loading or errors:

if (user === Loading)
  return <LoadingSpinner />;
if (user instanceof Error)
  return <ErrorPopup error={user} />;

And, to be honest, we don't really change those for each page. Usually we have the same behaviour through the whole app.

Well, hook can't just return those, so we need to wrap our component.

Example:

import { createLoader } from 'react-use-load';

const withLoader = createLoader(
  () => <LoadingSpinner />,         // on loading
  err => <ErrorPopup error={err} /> // on error
);

const UserPopup = ({ userId }) =>
  withLoader(() => fetchUser(userId), [ userId ])(
    user => {

      return user...; // render user data
    }
  )

In perspective of components they became much smaller. In case we need to load not only the user data, we can use Promise.all and load all we want.

This feature is experimental and I see it too complicated for now.

Lite version of useLoad()

Another way to deal with too much ifs is just to ignore errors. There is still onError callback if you need it, but hook itself will return just Loading in this case.

import useLoad from 'react-use-load';

const UserPopup = ({ userId }) => {
  const user = useLoadLite(
    () => fetchUser(userId),
    [ userId ],
    err => console.error(err)
  );

  if (user === Loading)
    return <LoadingSpinner />; // in case of error we will stuck here
  
  return user...; // render user data
}

onError is executed in useEffect so feel free to run setState inside.