Quick Basics of ReactJs, Redux & Redux-Saga

React (Docs)

  • React makes it painless to create interactive UIs.
  • Design simple views for each state in your application.
  • React is Declarative:
    • Imperative would say (like JQuery):
      • if (user.likes()) {
          if(!hasBlue()) {
             removeGrey();
             addBlue();
          }
        } else{
          if(hasBlue()) {
             removeBlue();
             addGrey();
          }
        }
        
    • Declarative would say:
      • if (this.state.liked) {
          return <bluelike/>;
        } else{
          return <greylike/>;
        }
        
  • We now can use ES6 and a summary of features is http://es6-features.org/
  • Component Life Cycles:
    • Mounting These methods are called when an instance of a component is being created and inserted into the DOM:
      • constructor()
      • componentWillMount()
      • render()
      • componentDidMount()
    • Updating An update can be caused by changes to props or state. These methods are called when a component is being re-rendered:
      • componentWillReceiveProps()
      • shouldComponentUpdate()
      • componentWillUpdate()
      • render()
      • componentDidUpdate()
    • Unmounting This method is called when a component is being removed from the DOM:
      • componentWillUnmount()
  • Build encapsulated components that manage their own state, then compose them to make complex UIs.
  • Webapck is another great packing tool, more on that: Getting started
  • React uses JSX for rendering HTML, which is Javascript + XML combination: Introducing JSX
  • React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that's not explicitly written in your application.
    • JSX Converts xml data into objects:
      • const element = (
          <h1 classname="greeting">
             Hello, world!
          </h1>
        );
        
    • Gets converted to
      • const element = React.createElement(
          'h1',
          {className: 'greeting'},
          'Hello, world!'
        );
        
  • React uses Components, which is the root of React to display and provide data, we do it via:
    • Functional based:
      • function Welcome(props) {
          return <h1>Hello, {props.name}</h1>;
        }
        
    • Class based:
      • class Welcome extends React.Component {
          render() {
             return <h1>Hello, {props.name}</h1>;
          }
        }
        
  • Using to state to manipulate the html, react renders when either props changes or state changes. State is used for component internal data management.
    • Best practices in state management, we should not manipulate the state variable directly:
    • // Wrong
      this.setState({
        counter: this.state.counter + this.props.increment,
      });
      
    • Instead use the callback for state management:
    • // Correct
      this.setState((prevState, props) => ({
        counter: prevState.counter + props.increment
      }));
      
  • Component event handling is ideally about, how well we can consume any change or click event on JSX. That said, each event trigger should then be sent across to state to be manipulated.
  • There are good practices for component render, we shouldn't be mutating objects in render, because the render method then keeps trigger further render cylces;
    • Not the best way:
      • // Not the best way
        class LoggingButton extends React.Component {
          handleClick() {
            console.log('this is:', this);
          }
        
          render() {
            // This syntax ensures `this` is bound within handleClick
            // The arrow function always creates a new anonymous function 
            // and hence a new function is passed as props hence the button
            // would be re-rendered even if it's props actually wouldn't change
            return (
              <button onClick={(e) => this.handleClick(e)}>
                Click me
              </button>
            );
          }
        }
        
    • The good way:
      • // The ideal way
        class LoggingButton extends React.Component {
          constructor(props) {
            super(props);
        
            this.handleClickEvent = this.handleClick.bind(this);
          }
        
          handleClick() {
            console.log('this is:', this);
          }
        
          render() {
             return (
               <button onClick={this.handleClickEvent}>
                 Click me
               </button>
             );
          }
        }
        
  • Keys - it help React identify which items have changed, are added, or are removed (list of rendering):
    • <ul>
        {
          props.posts.map((post) =>
           <li key={post.id}>
            {post.title}
           </li>
          )
        }
      </ul>
      
  • Controlled component: In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
    • class NameForm extends React.Component {
        constructor(props) {
            super(props);
            this.state = {value: ''};
         
            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }
      
        handleChange(event) {
            this.setState({value: event.target.value});
        }
      
        handleSubmit(event) {
            alert('A name was submitted: ' + this.state.value);
            event.preventDefault();
        }
      
        render() {
          return (
             <form onsubmit="{this.handleSubmit}">
                <label>
                 Name:
                 <input onchange="{this.handleChange}" 
                         type="text" value="{this.state.value}" />
             </label>
             <input type="submit" value="Submit" />
             </form>
            );
        }
      }
      
  • UnControlled components: Some times we need to access the components data and might not have the state to check the data being used, and which case we can use ref to fetch the data
  • Don't Overuse Refs: lifting the shared state up to their closest common ancestor
  • Important: There should be a single "source of truth" for any data that changes in a React application. Usually, the state is first added to the component that needs it for rendering. Then, if other components also need it, you can lift it up to their closest common ancestor. Instead of trying to sync the state between different components, you should rely on the top-down data flow.

Redux (Docs)

  • Redux is an implementation of "Facebook Flux". Flux is not a library or framework. It's simply a recommended architecture for web applications.
  • The entire application takes care of managing their values by keeping the data in the application level store.
  • Three principles:
    • Single source of truth
    • State is read-only
    • Changes are made with pure functions
  • Basics:
    • Actions: These are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().
    • Action Creators: These are exactly functions that create actions. It's easy to conflate the terms “action” and “action creator,” so do your best to use the proper term.
      • export const resetDataset = () => {
          return {
          type : ActionTypes.RESET_DATASET_DATA
          };
        };
        
    • Reducer: This is a pure function that takes the previous state and an action, and returns the next state.
    • function todoApp(state = initialState, action) {
        switch (action.type) {
           case SET_VISIBILITY_FILTER:
             return Object.assign({}, state, {
               visibilityFilter: action.filter
             })
           case ADD_TODO:
             return Object.assign({}, state, {
               todos: [
                 ...state.todos,
                 {
                   text: action.text,
                   completed: false
                 }
               ]
             })    
           default:
             return state
         }
      }
  • Store: Once we have the actions and the reducers in place, the orchestration is done by Store by bringing them together using "createStore" from redux and hence we get methods like:
    • getState of the application
    • dispatch the action to the reducer -- Mapped distpatch to props when using "connect"
    • subscribe the listeners -- Mapped state to props when using "connect"
  • Combine the reducers once we split them using combineReducer.

Redux Saga (Docs)

  • There are provisions in redux to create an ansyc api call and we can do it just with redux by keeping the reference to the store and using the store dispatch when the api returns back.
  • Then we would use the a middleware which takes care of intercepting all the actions and forwarding them to reducers.
  • Redux-Saga uses ES6 Generators and yield
  • There are some important methods which we should be aware of and use them:

Comments

  1. Hi,
    That is so logical and clearly explained. Keep it up! I follow up your blog for future post.
    Regards,
    Find Best ReactJS Online Training in India

    ReplyDelete
  2. Nice Explanation. Thanks for sharing this great information through your blog.
    React JS Training
    Node JS Training
    Full Stack online Training

    ReplyDelete
  3. I really appreciate your blog for Quick Basics of ReactJs, Redux & Redux-Saga. As a reactjs developer, I am happy to read this blog. But why reactjs web development company is not providing such kind of information to their developers, so that it can be helpful for both of us.

    ReplyDelete
  4. Thanks for sharing information...nice explanation for this blog...
    react js training in hyderabad

    ReplyDelete
  5. Very interesting blog. The way you wrote about React Js with various examples of Redux and Redux Saga is very nice. One can easily understand the basics of Reactjs by reading your blog. I was also looking to hire expert react js developer and got your blog. Thanks for sharing such a great blog.
    Please also check some React js development services India.

    ReplyDelete
  6. Here are the Top Mobile App Development Companies New York which produce excellent app development services along with additional services and resources that support any business demands.

    ReplyDelete

Post a Comment

Popular posts from this blog

SSH using Chrome Secure Shell app with SSH identity (private key and public key)

Load Testing using Apache Bench - Post JSON API

NGinx + Gunicorn + Flask-SocketIO based deployment.