Using too many useState hooks in react. How do I refactor this?

Viewed 5625

the useState hooks are great. I mainly use the useState hooks to initialise certain states, and I also pass the function to children components to change the states. However, I realise I am starting to use too many useState hooks in my parent page component. This looks and feels wrong, because I am starting to have about 6-10 useState hooks in the parent page component.
Without showing the code, Is there a better way to do this? Maybe a better practice, or a better way to refactor.
Thanks

1 Answers

Whenever you encounter a problem like this you should first look if you can split your component into multiple smaller ones. However there are scenarios where that's not an option. In those cases I would advice using useReducer.

// before

const {cache, setCache } = useState({});
const {posts, setPosts } = useState({});
const {loading, setLoading } = useState(false);

// Would become after refactor

const initialState = {
  cache: {},
  posts:{},
  loading: false
}

const [state, dispatch] = useReducer(reducer, initialState);
Related