Home > Enterprise >  Clean up code with multiple toggle states in reactjs
Clean up code with multiple toggle states in reactjs

Time:05-31

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!

CodePudding user response:

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
                })

CodePudding user response:

You can use a single state with an object that contains these values.

for example:

const [loadingStates, setLoadingStates] = useState({
    loading: true,
    loadingSave: false,
    loadingDelete: false,
    loadingDownload: false,
});

for changing the values, you can use:

setLoadingStates(prevObject => {
    return {
        ...prevObject,
        loading: false,
    }
});

Hope this helps

  • Related