Skip to content

Instantly share code, notes, and snippets.

@amsterdamharu
Last active March 17, 2021 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amsterdamharu/59e67f7248738d9b36067ac639f07c6c to your computer and use it in GitHub Desktop.
Save amsterdamharu/59e67f7248738d9b36067ac639f07c6c to your computer and use it in GitHub Desktop.
unnest react containers
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