For parent-child communication, simply pass props.
Use state to store the data your current page needs in your controller-view.
Example
class DummyComponent extends React.Component {
state = {
name: 'Manoj'
}
render() {
return <div>Hello {this.state.name}</div>;
}
}
Use props to pass data & event handlers down to your child components.
Example:
class DummyComponent extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
<DummyComponent name="Manoj" />
<DummyComponent name="Ajay" />
mapStateToProps
is used for selecting the part of the data from the store that the connected component needs. The mapStateToProps
function should always be written with at least state
passed in.
Example:
function mapStateToProps(state) {
return {
a: 42,
todos: state.todos,
filter: state.visibilityFilter,
}
}
import { connect, Provider } from 'react-redux';
import store from '../../systems/redux/store';
- By default, a connected component receives
props.dispatch
and can dispatch actions itself. connect
can accept an argument called mapDispatchToProps
, which lets you create functions that dispatch when called, and pass those functions as props to your component.
render() {
return <button onClick={() => this.props.toggleTodo(this.props.todoId)} />
}
const mapDispatchToProps = dispatch => {
return {
toggleTodo: todoId => dispatch(toggleTodo(todoId))
}
}
react-redux is the library that is passing these methods to your component as props.
dispatch() is the method used to dispatch actions and trigger state changes to the store. react-redux is simply trying to give you convenient access to it.
React Redux includes a <Provider />
component, which makes the Redux store available to the rest of your app:
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import App from './App'
const rootElement = document.getElementById('root')
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
)
useSelector
reads a value from the store state and subscribes to updates, while useDispatch
returns the store's dispatch
method to let you dispatch actions.
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
decrement,
increment,
incrementByAmount,
incrementAsync,
selectCount,
} from './counterSlice'
import styles from './Counter.module.css'
export function Counter() {
const count = useSelector(selectCount)
const dispatch = useDispatch()
return (
<div>
<div className={styles.row}>
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
+
</button>
<span className={styles.value}>{count}</span>
<button
className={styles.button}
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
-
</button>
</div>
{}
</div>
)
}