Skip to content

Instantly share code, notes, and snippets.

@renaudtertrais
Last active November 3, 2016 16:50
Show Gist options
  • Save renaudtertrais/00b7bd8737ec1d069bbe3c9acde8229d to your computer and use it in GitHub Desktop.
Save renaudtertrais/00b7bd8737ec1d069bbe3c9acde8229d to your computer and use it in GitHub Desktop.
StateFul functional React component proposal base on @sebmarkbage Stateful Functions https://git.io/vXnhF
/* ---------------------------------------------- *\
STATEFUL FUNCTIONAL REACT COMPONENT PROPOSAL
\* ---------------------------------------------- */
// event handler can return a state change
const handleClick = (props, state) => ({ value: state.value + 1 });
// event handler can return function in order to do a async state change
const handleClickAsync = (props, state) => setState => {
// setState after 1s
setTimeout(() => setState({ value: state.value + 1 }), 1000);
};
// can return nothing or an empty object in order to not change the state
const handleClickQuiet = () => {
doSomething();
return {};
}
// Stateful component
const Counter =(props, state) => (
<div>
<h1>{state.value}</h1>
<button onClick={handleClick}>+1</button>
<button onClick={handleClickAsync}>+1 async</button>
<button onClick={handleClickQuiet}>quiet event</button>
</div>
);
// --- Optionnal --- : LifeCycle Callbacks
// LifeCycle callback functions behave just as event listeners
// return direcly a state change
// here it is like getInitialState() behavior
React.on(Counter, 'componentWillMount', (props, state) => ({ value: props.value || 0 });
// return function in order to do a async state change
React.on(Counter, 'componentWillReceiveProps', (props, state, newProps) => setState => {
if (newProps.value !== props.value) {
setTimeout(() => setState({ value: newProps.value}), 0);
}
}
// return nothing or an empty object in order to not change the state
React.on(Counter, 'componentDidUpdate', (props, state, oldProps, oldState) => {
doSomething();
}
<Counter value={0} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment