Skip to content

Combining related state variables #81

Description

@oliverjam

mixlist/pages/profile.js

Lines 20 to 29 in a569898

const [loading, setLoading] = useState(true);
const [username, setUsername] = useState(null);
const [reviewsTotal, setReviewsTotal] = useState(null);
const [followedAlbums, setFollowedAlbums] = useState(null);
const [usersReview, setUsersReview] = useState([]);
const [usersReviewArtwork, setUsersReviewArtwork] = useState([]);
const [userFavAlbums, setUserFavAlbums] = useState([]);
const [ratings, setRatings] = useState(null);
const [profile_img, setProfileImg] = useState(null);

When you have a bunch of state variables like this that are all related it can be easier to keep them in a single value (usually an object). E.g.

function ProfilePage() {
  // ...
  const [profile, setProfile] = useState({
    loading: true,
    reviews: [],
    // ...
  });
}

You can then set the whole object in one go like:

getProfile().then(data => setProfile(data))

or update single properties (maintaining all the others) like:

setProfile(oldProfile => ({ ...oldProfile, loading: false }));

If you wanted to go even further you could try using a "reducer" via React's useReducer hook. This is a lower-level state primitive designed for centralising a bunch of updates in one place. An example might be a little long, so I'd recommend looking at the docs if you're interested. https://reactjs.org/docs/hooks-reference.html#usereducer

Activity

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

Metadata

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