AgileĀ  Study Group #2

Advanced React Pattern

What I learned

React.Children.Map & cloneElement

React.Children.map(this.props.children, childElement => {
  return React.cloneElement(childElement, {
  on: this.state.on,
  toggle: this.toggle,
  });
})

Improved just mounted

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}
const useToggle = (onToggle) => {
  const [state, setState] = useState(false);
  const preState = usePrevious(state);
  const toggle = useCallback(() => setState(state => !state), []);
  useEffect(() => { 
    if (preState !== undefined && preState !== state) {
      onToggle(state);
    }
  }, [state]);
  return [state, toggle];
}

Improved just mounted

const useToggle = (onToggle) => {
  const [state, setState] = useState(false);
  const justMounted = useRef(true);

  const toggle = useCallback(() => setState(state => !state), []);

  useEffect(() => { 
    if (!justMounted.current) {
      onToggle(state);
    }
    justMounted.current = false
  }, [state]);

  return [state, toggle];
}

Compound Component

By Stanney Yen

Compound Component

  • 293