Advanced React Pattern
React.Children.map(this.props.children, childElement => {
return React.cloneElement(childElement, {
on: this.state.on,
toggle: this.toggle,
});
})
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];
}
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];
}