Successfully reported this slideshow.

React + Redux Introduction



Upcoming SlideShare
React JS and Redux
React JS and Redux
Loading in …3
1 of 47
1 of 47

React + Redux Introduction



Download to read offline

Introduction to React in combination with Redux. Redux helps you to develop applications in a simple way while having features like time-travel available during development.

Introduction to React in combination with Redux. Redux helps you to develop applications in a simple way while having features like time-travel available during development.

More Related Content

Related Books

Free with a 14 day trial from Scribd

See all

React + Redux Introduction

  1. 1. React + Redux
  2. 2. React + Redux @nikgraf Nik Graf @nikgraf Creator of Belle (UI Components) Working with StarterSquad Travelled around the World
  3. 3. React + Redux @nikgraf ECMAScript2015 const sum = (first, second) => { return first + second; }
  4. 4. React + Redux @nikgraf Created by Sebastian McKenzie - ECMAScript 2015 Support, JSX Support - Widely adopted
  5. 5. Let’s get started Source:
  6. 6. React + Redux @nikgraf React React is a JavaScript Library for building user interfaces. • Focus on the UI, not a Framework • One-way reactive data flow (no two-way data binding) • Virtual DOM
  7. 7. React + Redux @nikgraf Virtual DOM Keep track of state in DOM is hard. The DOM API is slow. (Try to re-render the whole DOM on every change)
  8. 8. React + Redux @nikgraf Virtual DOM Source:
  9. 9. React + Redux @nikgraf Virtual DOM Source:
  10. 10. React + Redux @nikgraf Virtual DOM Benefits Batched DOM read/write operations. Efficient update of sub-tree only.
  11. 11. React + Redux @nikgraf Our first Experiment Part I <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="bundle.js"></script> </head> <body> <div id="example"></div> </body> </html> index.html
  12. 12. React + Redux @nikgraf Our first Experiment Part II import React from 'react'; import ReactDOM from 'react-dom'; const exampleElement = document.getElementById('example'); ReactDOM.render(<h1>Hello, world!</h1>, exampleElement); main.js -> bundle.js
  13. 13. React + Redux @nikgraf JSX JSX is a JavaScript syntax extension that looks similar to XML. // Input (JSX): var app = <Nav color="blue" />; // Output (JS): var app = React.createElement(Nav, {color:"blue"});
  14. 14. React + Redux @nikgraf Rendering a Component import React from 'react'; import ReactDOM from 'react-dom'; const App = () => { return (<p>Hello World!</p>); } const exampleNode = document.getElementById('example'); ReactDOM.render(<App />, exampleNode); main.js -> bundle.js
  15. 15. React + Redux @nikgraf <body> <div id="example"> <p> <!-- App start --> Hello World! </p> <!-- App end --> </div> </body> index.html Rendering a Component
  16. 16. React + Redux @nikgraf Nested Components Part I import React from 'react'; const Profile = ({avatar, name}) => { return ( <div> <img src={avatar} /> <span>{name}</span> </div> ); } profile.js
  17. 17. React + Redux @nikgraf import React from 'react'; import ReactDOM from 'react-dom'; import Profile from ‘./profile'; const App = () => { return ( <div> <h1>Hello World!</h1> <Profile avatar="http://test.png" name="Nik" /> </div> ); } const exampleNode = document.getElementById('example'); ReactDOM.render(<App />, exampleNode); main.js -> bundle.js Nested Components Part II
  18. 18. React + Redux @nikgraf <body> <div id="example"> <div> <!-- App start --> <h1>Hello World!</h1> <div> <!-- Profile start --> <img src="http://test.png" /> <span>Nik</span> </div> <!-- Profile end --> </div> <!-- App end --> </div> </body> index.html Nested Components Part III
  19. 19. React + Redux @nikgraf Stateless Function Components Functional Programming: - avoid changing-state - avoid mutable data - calling a function twice with the same values as arguments will produce the same result Stateless Function Components: - avoid changing-state - avoid mutable data - calling a function twice with the same values as arguments will produce the same result
  20. 20. React + Redux @nikgraf Wait, but why? Predictable easy to understand & easy to test
  21. 21. React + Redux @nikgraf
  22. 22. React + Redux @nikgraf If/Else const Profile = ({name, isOnline}) => { let onlineIndicator; if (isOnline) { onlineIndicator = (<span>green</span>); } else { onlineIndicator = (<span>red</span>); } return ( <div> {name} {onlineIndicator} </div> ); } profile.js
  23. 23. React + Redux @nikgraf If/Else <Profile name="Nik" isOnline={false}/> <div> Nik <span>red</span> </div>
  24. 24. React + Redux @nikgraf Loop const FriendList = ({friends}) => { return ( <ul> { => { return <li>{}</li>; })} </ul> ); } friendlist.js
  25. 25. React + Redux @nikgraf Loop const friends = [ { name: 'Max'}, { name: 'Tom'}, ]; <FriendList friends={friends} /> <ul> <li>Max</li> <li>Tom</li> </ul>
  26. 26. React + Redux @nikgraf React Summary - We can create out own components - We can nest components as we like - Stateless Function Components are pure - We can control flow via JS (if, else, for, map …)
  27. 27. React + Redux @nikgraf Interaction const Profile = ({name}) => { return ( <div> {name} <button onClick={ console.log('Clicked!'); }> Click me! </button> </div> ); } profile.js
  28. 28. React + Redux @nikgraf What to do with interactions like onMouseOver, onSubmit & onClick?
  29. 29. React + Redux @nikgraf Redux to rescue! Redux allows you to manage the state with a minimal API but completely predictable behaviour.
  30. 30. React + Redux @nikgraf What about Flux? Source:
  31. 31. React + Redux @nikgraf Basic Principle (previousState, action) => newState
  32. 32. React + Redux @nikgraf
  33. 33. React + Redux @nikgraf Redux Flow Store Action Creators React Components Reducers Interaction e.g onClick dispatch(action) (newState) (state) (previousState, action)
  34. 34. React + Redux @nikgraf Feels like Fear just turned into a Superpower
  35. 35. React + Redux @nikgraf Action const action = { type: 'ADD_TODO', text: 'Call Mom', }
  36. 36. React + Redux @nikgraf Action Creator function addTodo(text) { const trimmedText = text.trim(); return { type: 'ADD_TODO', text: trimmedText, } } <button onClick={ dispatch(addTodo('Call Mom ') }> Add Todo </button> actions.js
  37. 37. React + Redux @nikgraf Reducer const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, { text: action.text, completed: false } ] default: return state } } reducers.js
  38. 38. React + Redux @nikgraf Store import { createStore } from 'redux' import todoReducer from '../reducers' let store = createStore(todoReducer); store.subscribe(() => console.log(store.getState()) ) store.dispatch(addTodo('Learn about reducers')); store.dispatch(addTodo(‘Call Mom'));
  39. 39. React + Redux @nikgraf Connect React with Redux import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import todoApp from './reducers'; import App from './containers/App'; let store = createStore(todoApp); let exampleNode = document.getElementById('example'); ReactDOM.render( <Provider store={store}><App /></Provider>, exampleNode );
  40. 40. React + Redux @nikgraf Connect React +Redux import React from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions.js'; const App = ({dispatch, state}) => { return ( <button onClick={ dispatch(addTodo('Call Mom') }> Add Todo </button> ); }; export default connect(App);
  41. 41. React + Redux @nikgraf Redux Summary - Redux allows you to manage the state with predictable behaviour. - (previousState, action) => newState
  42. 42. React + Redux @nikgraf
  43. 43. React + Redux @nikgraf Time-travel Demo
  44. 44. React + Redux @nikgraf Why this Stack? - Reusable Components - Predictable Code (functional) - TimeTravel - Performant & lightweight
  45. 45. React + Redux @nikgraf Is it production ready? React - used by Facebook, Firefox, Airbnb and many more Redux - used by Firefox, Docker, Technical University of Vienna, Mattermark and many more - “Love what you’re doing with Redux” Jing Chen, creator of Flux
  46. 46. Vienna React Meetup Source:
  47. 47. React + Redux @nikgraf The End Thanks for listening! Vienna React Meetup

Editor's Notes

  • Hello everybody, I'm Nik and today I will tell you about React in combination with Redux.
  • A brief heads up what I do:

    Creator of Belle - React UI Components with over 1000 Github stars

    I'm Member & Team Lead of a freelancer community called StarterSquad.
    There we form teams to work with Startups and Science projects.

    As the teams I'm working with are spread over the globe I have the chance to travel a lot.
  • I need to warn you upfront.

    In the code examples I will use ES20 15 syntax which got approved a few months back.

    This is a function all with 2 arguments. It creates the sum of them and returns the value.
    As you can see we assign it to a variable. const is a one-time assignable block scoped binding construct.
  • And while browsers don't implement it yet we already can use it because compilers like Babel can compile it to EcmaScript5. The version that runs in the Browser of all your customers.
  • * Who of you ever has built something with React?
    * Who of you considers to use if for your next React?
  • Significant features of react:
    - It's a UI Library. It is not a full fleshed front-end framework. There is no routing, no data fetching.
    - One-way reactive data flow! You can't change data of parent.

    WHAT? Sound like a basic templating language.
  • Manual DOM manipulation is messy and keeping track of the previous DOM state is hard.

    A solution to this problem is to write your code as if you were recreating the entire DOM whenever state changes. Of course, if you actually recreated the entire DOM every time your application state changed, your app would be very slow and your input fields would lose focus.
  • React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native.
  • So when something happens in your data model React will figure out the diff and just update the necessary changes in the real DOM
  • This gives us:

    Batched DOM read/write operations.
    Efficient update of sub-tree only.
  • This is our index.html file. Nothing fancy. We load a script called bundle.js - it’s our compiled output from Babel.
    In addition with have one div with the ID example
  • Here we have our main.js which is compiled to bundle.js
    What we do here is to render a headline with Hello World!
    We get the div with id example and use ReactDOM to render our headline into it.

    You might have 2 remarks here: why ReactDOM? Because we have different rendering targets. There is ReactCanvac, ReactNative and so on

    The second remark is probably: what the hack are you doing with html in JavaScript. That doesn’t work
  • JSX is compiled with babel and allows us to simply use a XML like syntax in JS code simply for convenience.

    What about best practices of not mixing html & js. Well I’m sorry to tell, but that’s not the case anymore for React.
  • Ok, done with the basics. Let’s get to some interesting things. Let us create a component that can used.

    We can create a component by just returning JSX from a function. Voila we have a component. We now can use this component.
  • This is the output :) Pretty simple (go back)
  • Let’s render dynamic content in a component by providing parameters.

    You can see here we create a profile component. The first argument of a component is always the properties. We can deconstruct them directly and use in our JSX code.

    Here we provide the avatar as a src for the image and the name is rendered directly into a span.
  • Now we can import an use our component and use it anywhere else in JSX code. Here we use it inside a div. and we pass in the parameters it expects.

    Then we render the whole thing again
  • Here I marked where the App component starts and end as well as where the Profile component starts and ends
  • What I have shown you until now is actually pretty new. These function declarations are called stateless function components. There is a Component class in React as well that can have state, but you should use it carefully.

    Certain traits of function programming.
    Oh, it looks the same!
  • Because it makes our code predictable and this leads to code that is easy to understand & and easy to test as well.
  • So I hope by now you should be in this state!
  • Of course we want to control the flow as well. So we can do if/else simply with js.

    Based on the isOnline parameters we assign onlineIndicator different html code.
    If the isOnline parameter changes the html output will change.
  • Of course you can loop as well.
    Here we simply iterate over all the friends and return a list element for each of them.
  • On things is missing! Interactions by the user.
    We provide the interaction callback as parameter to the button tag.
  • But what do with these interactions? How can we change the parameters passed down to these components and actually create an effect?
  • Redux for rescue
  • Well, you might heard of Flux. It’s this application concept developed by Facebook which works well with React.

    From Flux we evolved into two directions: Redux & Relay
  • Interestingly since quite some time in Web Development we learned to keep the data in one place. We don't store our data somewhere in memory or code. No, we have a database and when you do a request the application runs and gives you back a response. It's like a big function.

    Redux follows the same principle. It has one central place for your complete app state. That right now might scare the hell out of you.
  • What is this guy talking? are you crazy? you want to keep all the app state in one object?

    Don't worry, it all will be fine.
  • Let me give you a brief overview about how it works.

    The core of redux its the store instance. It is responsible to for keeping the application state. As you can see here the store provides the state to our react components and they render accordingly. When the user triggers an interaction like she clicks on a button we dispatch an actions. This action is passed to the reducers which create a new application state and return it to the store. That again influences the rendering. The cycle is complete.
  • ideally that felt you have superpower. to be honest it took ma bit of time to get why the concept is great & important
  • Let’s look at the building blocks. How does the code look like.

    First we have actions. Pretty simple just an JS object. The only thing important is that an action must have a type. Data is optional.
  • We use action creators to create these actions an ideally do something with the data.

    API calls also come here.
  • In the reducers we get the state passed in and then depending on the action type we manipulate the data. Get from one state to the next.

    Think about we reducing the passed state + the action to the new state. In this case we simply create a new arrays with the an action appended to it. By default it is marked as not completed. You can see we leverage the text of the actions here.
  • The last pice in the puzzle is the store. It is initialised with the reducers. In our case the todo
    You can subscribe to it and when you dispatch a new action it will inform the subscribers.
  • To make it work we need to wrap our App with a custom Provider component.
  • To connect the store with our react components we wrap our root App component with a connect. Then you get the dispatch function from the store + state.

    To be honest that’s a bit of magic I don’t want to dive into too deep, but it works like a charm.
  • Because of
  • Ok, but why all the hassle with the actions and reducers?
    One single entry point for changes + timetravel
  • Speakers like Christopher Pojer who is in Facebooks JavaScript Infrustructure Team (5 people).
  • Thanks for listening
    Feel free to ask me any questions
  • ×