Skip to content

Instantly share code, notes, and snippets.

@StevenMDixon
Created October 5, 2018 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenMDixon/8f3370861548c8f051aa2d63ebac1f51 to your computer and use it in GitHub Desktop.
Save StevenMDixon/8f3370861548c8f051aa2d63ebac1f51 to your computer and use it in GitHub Desktop.

Redux

State management.

Models applications state as a single JS object

npm install --save redux

Action

a plain javascript objec

{
  type: "LOGOUT_USER"
}

Reducer

Decides which state to return based on the current state and the action.

function rootReducer(state={}, action) {
  //can switch what state is returned based on action;
  return state; 
}

Store

a store is one big javascript object that holds the state for the entire application

const store = Redux.createStore(rootReducer);

changing the state

store.dispatch({
 type: "LOGIN_USER"
})

get the state

store.getState();

Listening for changes

redux accepts a callback through a listen function

const changeCallback = () =>{
  console.log("something changed");
  store.getState();
}

const unsubscribe = store.listen(changeCallback);

now whenever the state changed the callback will be called.

flow

dispatch(action) reducer(currentstate, action) newState Invoke Listeners (UI Changes)

React with Redux

React-Redux is a library used to integrate react with redux.

exposes a provider component and a connect function.

Handles: Listeners, passing in state to a component.

install

install --save react-redux

Provider

Wrap your top level app in Tags and create a store.

  const store = createStore(rootReducer);
  
  ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>, document.getElementById('root');
  )

Connect

connect (getthestate, callanaction)(name of component)

mapstatetoprops - needs state

const MapStateToProps = state => ({name: state.name})

export default connect(mapStateToProps, null)(BoldName);

mapDispatchToProps - dispatches action

const DelName = ({delName}) => (
  <button type="button" onClick={delName}>Delete</button>
)

mapDispatchToProps =(dispatch, ownProps) => (
  {
    delName: () =>(dispatch(
    {
      type: "DEL_NAME"
    }
    ))
  }
)

export default connect(null, mapDispatchToProps) (DelName);

presentational Component

"Dumb" component or stateless functional component show things in regards to the ui

Container Component

stateful component that deals with application data

often created using higher order componenets

combineReducers

Each reducer is only responsible with its state;

const rootReducer = combineReducers({
currentUser,
messages,
});

Redux Directory Structure

src actions components containers reducers index.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment