How to change props to state in React Hooks?

前端 未结 4 1725
温柔的废话
温柔的废话 2021-02-02 07:41

In Simple react class component we used to change the props to state this way:

constructor(props) {
    super(props)

    this.state = {
      pitch: props.book         


        
4条回答
  •  青春惊慌失措
    2021-02-02 08:32

    It is difficult to achieve a state which depends on prop value and at the same avoid unnecessary re-renders.

    Here is my attempt in creating such a hook:

    /**
     * Replacement for useState which depends on prop value and avoids unnecessary re-renders.
     */
    export function useStateBasedOnProps(propValue) {
        const [, update] = useState(false);
    
        const [state, setState] = useMemo(() => {
            const state = {};
            return [
                state,
                (value) => {
                    if (value instanceof Function) {
                        state.value = value(state.value);
                    } else {
                        state.value = value;
                    }
                    update((tick) => !tick);
                }
            ];
        }, [update]);
    
        if (state.prevPropValue !== propValue) {
            state.prevPropValue = propValue;
            state.value = propValue;
        }
    
        return [state.value, setState];
    }
    

    Here is a usage example:

    function IncButton({initialValue}) {
        const [value, setValue] = useStateBasedOnProps(initialValue);
        const increment = useCallback(() => setValue((prev) => prev + 1), [setValue]);
        return ;
    }
    

    Full example: https://gist.github.com/mdevils/b861610780300784292194f65886517a

提交回复
热议问题