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.
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. 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. React + Redux @nikgraf
Virtual DOM
Source: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
9. React + Redux @nikgraf
Virtual DOM
Source: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
10. React + Redux @nikgraf
Virtual DOM Benefits
Batched DOM read/write operations.
Efficient update of sub-tree only.
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. 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. 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"});
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. React + Redux @nikgraf
Wait, but why?
Predictable
easy to understand
&
easy to test
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 …)
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. 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
);
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
47. React + Redux @nikgraf
The End
Thanks for listening!
https://github.com/nikgraf
https://twitter.com/nikgraf
Vienna React Meetup
http://www.meetup.com/Vienna-ReactJS-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