Skip to content

Instantly share code, notes, and snippets.

@hitsthings
Last active September 1, 2018 10:34
Show Gist options
  • Save hitsthings/50f61545eb9db8455d4e9d52f15a1a01 to your computer and use it in GitHub Desktop.
Save hitsthings/50f61545eb9db8455d4e9d52f15a1a01 to your computer and use it in GitHub Desktop.
Logic outside of React
// -- bit excessive for this case, but the example isn't realistic in the first place
export const probability = () => Math.random();
// -- some other file
export const diceRoll = () => Math.ceil(probability() * 6);
// -- some other file
export const coinFlip = () => probability() > 0.5 ? 'heads': 'tails';
// -- shared state can be stored however you like (this is just one example)
export let wisdom = diceRoll();
const callbacks = [];
export const listen = callback => callbacks.push(callback);
export const rollForWisdom = () => {
wisdom = diceRoll();
callbacks.forEach(cb => cb(wisdom));
};
// -- still consumable in React, or anywhere. Can share state with non-React code too.
class Probability extends Component {
constructor(props) {
super(props);
this.state = wisdom;
listen(wisdom => this.setState(wisdom));
}
render() {
return this.props.children({ rerun: rollForWisdom, result: this.state });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment