Skip to content

Instantly share code, notes, and snippets.

@RoyalIcing
Created June 29, 2018 02:02
Show Gist options
  • Save RoyalIcing/8f5ad1b41352cf1e4685d1ec359eae9f to your computer and use it in GitHub Desktop.
Save RoyalIcing/8f5ad1b41352cf1e4685d1ec359eae9f to your computer and use it in GitHub Desktop.
React state management ideas
interface State {
counter: number
}
const counterModel = {
initial(): State {
return {
counter: 0
};
},
increment({ counter }: State): State {
return {
counter: counter + 1
};
},
decrement({ counter }: State): State {
return {
counter: counter + 1
};
},
async incrementDelayed({ counter }: State): Promise<State> {
await new Promise(resolve => setTimeout(resolve, 500));
return {
counter: counter + 1
};
}
};
///
import React from 'react';
class SmartComponent extends React.Component<{}, State> {
state = counterModel.initial()
counterHandlers = localStateHandlers(this, counterModel)
}
///
const reducer = combineReducers({
counter: makeReducer(counterModel)
});
const actions = makeActions(counterModel, (name) => `COUNTER_${name}`)
///
const { Provider, Consumer } = makeContext({
counter: counterModel
})
<Provider>
<Consumer>
{({ counter }) => <div>
<button onClick={counter.increment}>Increment</button>
</div>}
</Consumer>
</Provider>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment