Last active
March 17, 2021 19:13
-
-
Save amsterdamharu/59e67f7248738d9b36067ac639f07c6c to your computer and use it in GitHub Desktop.
unnest react containers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
const useContainer = (props, container) => { | |
return container(props); | |
}; | |
const Counter = ({ counter, up }) => { | |
const r = React.useRef(0); | |
r.current++; | |
return ( | |
<button onClick={up}> | |
{counter} rendred: {r.current} | |
</button> | |
); | |
}; | |
const Half = ({ counter, up }) => { | |
const props = React.useMemo( | |
() => ({ | |
counter: counter / 2, | |
up, | |
}), | |
[counter, up] | |
); | |
return useContainer(props, Counter); | |
}; | |
const PlusOne = ({ counter, up }) => { | |
const props = React.useMemo( | |
() => ({ | |
counter: counter + 1, | |
up, | |
}), | |
[counter, up] | |
); | |
return useContainer(props, Half); | |
}; | |
const Double = ({ counter, up }) => { | |
const props = React.useMemo( | |
() => ({ | |
counter: counter * 2, | |
up, | |
}), | |
[counter, up] | |
); | |
return useContainer(props, PlusOne); | |
}; | |
const CounterContainer = (props) => | |
useContainer(props, Double); | |
function App() { | |
const [counter, setCounter] = React.useState(0); | |
const up = React.useCallback( | |
() => setCounter((counter) => counter + 1), | |
[] | |
); | |
return <CounterContainer up={up} counter={counter} />; | |
} | |
ReactDOM.render(<App />, document.getElementById('root')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment