React Hooks useState() with Object

前端 未结 9 1672
猫巷女王i
猫巷女王i 2020-12-02 06:04

What is the correct way of updating state, is a nested object, in React with Hooks?

export Example = () => {
  const [exampleState, setExampleState] = use         


        
9条回答
  •  温柔的废话
    2020-12-02 06:58

    Initially I used object in useState, but then I moved to useReducer hook for complex cases. I felt a performance improvement when I refactored the code.

    useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

    useReducer React docs

    I already implemented such hook for my own use:

    /**
     * Same as useObjectState but uses useReducer instead of useState
     *  (better performance for complex cases)
     * @param {*} PropsWithDefaultValues object with all needed props 
     * and their initial value
     * @returns [state, setProp] state - the state object, setProp - dispatch 
     * changes one (given prop name & prop value) or multiple props (given an 
     * object { prop: value, ...}) in object state
     */
    export function useObjectReducer(PropsWithDefaultValues) {
      const [state, dispatch] = useReducer(reducer, PropsWithDefaultValues);
    
      //newFieldsVal={[field_name]: [field_value], ...}
      function reducer(state, newFieldsVal) {
        return { ...state, ...newFieldsVal };
      }
    
      return [
        state,
        (newFieldsVal, newVal) => {
          if (typeof newVal !== "undefined") {
            const tmp = {};
            tmp[newFieldsVal] = newVal;
            dispatch(tmp);
          } else {
            dispatch(newFieldsVal);
          }
        },
      ];
    }
    

    more related hooks.

提交回复
热议问题