Last active
July 10, 2018 17:36
-
-
Save drcmda/e71c10a1e2e45f73ef2e9b10e62f1c48 to your computer and use it in GitHub Desktop.
Aping Redux with context
This file contains 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
import React, { Component, PureComponent } from 'react' | |
import { render } from 'react-dom' | |
const { Provider, Consumer } = React.createContext() | |
class RenderPure extends PureComponent { | |
render() { | |
return this.props.children | |
} | |
} | |
class Store extends Component { | |
state = { | |
users: { | |
1: { id: 1, name: 'Max' }, | |
2: { id: 2, name: 'Catherine' } | |
}, | |
ids: [1, 2], | |
setState: this.setState.bind(this) | |
} | |
render() { | |
return ( | |
<Provider | |
value={this.state} | |
children={<RenderPure children={this.props.children} />} | |
/> | |
) | |
} | |
} | |
class User extends PureComponent { | |
change = e => { | |
const name = e.target.value | |
const { id, set } = this.props | |
set(state => ({ | |
users: { ...state.users, [id]: { ...state.users[id], name } } | |
})) | |
} | |
render() { | |
const { name, id } = this.props | |
console.log(`component ${id} renders`) | |
return ( | |
<div> | |
<input value={name} onChange={this.change} /> | |
{name} | |
</div> | |
) | |
} | |
} | |
class Users extends PureComponent { | |
render() { | |
return this.props.ids.map(id => ( | |
<Consumer | |
key={id} | |
children={store => <User {...store.users[id]} set={store.setState} />} | |
/> | |
)) | |
} | |
} | |
function App() { | |
return ( | |
<Store> | |
<Consumer children={store => <Users ids={store.ids} />} /> | |
</Store> | |
) | |
} | |
render(<App />, document.getElementById('root')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment