Search code examples
reactjscoding-styleantd

Clean up code with multiple toggle states in reactjs


I have a couple of buttons with antd library and want to add the loading state for each. I create multiple states to control those loadings

const [loading, setLoading] = useState(true);

const [loadingSave, setLoadingSave] = useState(false); //for save button

const [loadingDelete, setLoadingDelete] = useState(false); //for delete button

const [loadingDownload, setLoadingDownload] = useState(false); //for download button

This works but it seems my code is quite messy. If there are more buttons that need loading animation, it just becomes worse. Is there anyway to refactor this? Thank you in advance!


Solution

  • One clean way is to use React hook useReducer adding more states will be easier and more clean. To master useReducer check this blog https://blog.logrocket.com/react-usereducer-hook-ultimate-guide/

    In the React documentation React does not advice using one useState with an object of data

    It advices to using multiple useState.

        
        
        const initialState = {
            loading: true,
            loadingSave: false,
            loadingDelete: false,
            loadingDownload: false,
        };
       
       
       function handlingStatesReducer(state, action) {
            switch (action.type) {
                case 'setState': {
                    return {
                        ...state,
                        [action.fieldName!]: action.payload,
                    };
                }
                default:
                    return state;
            }
        }
        
        
        
        const [state, dispatch] = useReducer(handlingStatesReducer, initialState);
        const { loadingDownload, loadingDelete, loadingSave, loading } = state;
        
        
        /// To setState 
        
          dispatch({
                        type: "setState",
                        fieldName: "loading",
                        payload: false
                    })