In case you missed out the basic for redux, you can Find it Here
A Redux Store consists of a few different parts. You always have a single store, that uses either a single Reducer or Multiple Reducers (through Redux’s CombineReducers method). And you dispatch actions to your reducers. (You also have the initial state for each reducer, that is the default values).
- Store is like an instance of a class. It contains the actual data.
- A reducer takes the current state + an action, applies it to the state and returns the new state.
const initial_state = { data: 0 } const reducer = (state = initialState, action) => { switch (action.type) { case 'INC': return Object.assign({}, state, {data: state.data + action.NUMBER}) case 'DEC': return Object.assign({}, state, {data: state.data - action.NUMBER}) default: return state } } function incrementData(dispatch) { dispatch({TYPE: 'INC', NUMBER: 1}) } function decrementData(dispatch) { dispatch({TYPE: 'DEC', NUMBER: 1}) } const store = createStore(reducer) //You can now send actions to the store, by using the store.dispatch method, or reading the current state by using store.getState()
If you look in the Code above you see everything you need to set up a basic redux setup. You can make it how simple or complex you want to. I personally just make multiple reducers, and action-creator methods that update them.
The awesome thing about redux is that it isn’t a “react thing”. This means that you could use the same state layer with any front end library or framework.
If you want to use it with react then you need two things from the react-redux package: Provider and Connect.
You place the around the JSX code in your ReactDOM render() method in your entry point. And then you use the connect() method to map functions and state elements to your components.
You map state elements to your components so that what is in redux are passed as props to your components, and you map your action creators to your component through connect so that the action creators have access to your store’s dispatch method.
Something like this:
connect(state => ({element: state.element }), dispatch => ({myActionCreator: () => myActionCreator(dispatch)})(MyComponent)
As usual, the code above is working, but you need to add some imports etc to have a working example.
Arif Khoja is a Developer. He is a Javascript Enthusiatic who loves logical programming and has first hand experience in building a cutting edge internet product using Angular. He is also an open source freak and keen about learning and sharing. He writes Javascript both frontend and backend. He loves learning and sharing tech all the time. He also has a hands on experience in SEO and writes articles about latest emerging technologies.
1 comment