Redux
flowchart LR
subgraph a[src]
subgraph b[actions]
A[index.js]
end
subgraph c[reducers]
B[index.js]
C[selected.jsx]
end
D[App.js]
E[index.js]
end
b --> D;
c --> E;
C --> B;
D --> E;
reducers
# selected.jsx
const selectedReducer = (state="",action) => {
switch(action.type){
case "assign":
return action.payload;
default:
return state;
}
}
export default selectedReducer;
# ============================================ #
# index.js
import selectedReducer from './selected';
import {combineReducers} from 'redux'
const allReducers = combineReducers({
selected: selectedReducer
})
export default allReducers
actions
# index.js
export const assign = (topic) => {
return {
type: 'assign',
payload: topic
}
}
src
# index.js
import {createStore} from 'redux';
import allReducer from './reducers'
import {Provider} from 'react-redux'
const store = createStore(allReducer);
ReactDOM.render(<Provider store={store}><App/></Provider>
, document.getElementById("root"))
# ============================================ #
# App.js
### Access props everywhere
import {useSelector} from 'react-redux';
const selected = useSelector(state=>state.selected)
### Change props
import {assign} from './actions';
import {useDispatch} from 'react-redux';
const dispatch = useDispatch();
useEffect(()=>{
dispatch(assign("Image Annotation"))
},[dispatch])
References