-
-
Save RoyalIcing/8f5ad1b41352cf1e4685d1ec359eae9f to your computer and use it in GitHub Desktop.
React state management ideas
This file contains hidden or 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
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