From your comment you want both Todo
components to reference the same data i.e. if you add a Todo to one list you want if reflected in the other. This means they share the same data, which actually simplifies things.
Classes simplified for brevity
class Store extends EventEmitter {
constructor() {
super()
this.data = [ 'a', 'b', 'c' ]
}
mutate( index, value ) {
this.data[ index ] = value
this.onChange()
}
onChange() {
this.emit( 'change', this.data )
}
}
var store = new Store()
class MyComponent extends React.Component {
constructor( props ) {
super( props )
this.state = store.data
}
componentWillMount() {
store.on( 'change', data => this.setState( data ) )
}
}
setTimeout( () => {
store.mutate( 1, 100 )
}, 1000 )
In this trivial example the key is that instances of MyComponent
are listening for changes to the underlying data store (you could achieve the same by registering callbacks, or employing a Flux-style dispatcher, or many other methods). When the data changes, it emits and event and passes the data to any subscribers. In this case the subscribers take the data and set their state which triggers a re-render to keep your UI in sync.
If you actually want to reuse your Todo
component so that you can have several Todo lists in your app then you’ll just have to have a way to differentiate between the data that components require. A very simple way of achieving this would be to trigger a function that requests a data source from your store (rather than hard-coding as in the example), any requests to change data would then need to identify the correct data source but the UI would remain consistent through listening and responding to mutation events.