1
Let’s mix some HTML and JS together
React & Redux
advanced
2
Agenda
Project update - design system and usage
Design systems
Component lifecycle
React - additional hooks & optimization
Redux advanced
Landing and dashboard
React advanced
3
Project update - design system and usage
Definition of Design system
4
What are
Design systems?
The single source of truth which groups all
the elements that will allow the teams to
design, realize and develop a product.
It’s not a deliverable, but a set of deliverables.
“A kit of UI components without accompanying philosophy,
principles, guidelines, processes, and documentation is like
dumping a bunch of IKEA components on the floor and saying
“Here, build a dresser!”
The guidelines and documentation accompanying the
components serve as the instruction manual that come with the
IKEA components to help the user properly and successfully build
furniture.”
Quote
5
Brad Frost
Reasons why
6
Why working with
Design System?
● Reduce inconsistency
● Focus on the user
● Faster prototyping
● Quick iteration
Javascript practices - old and new
7
Multiple free and open source design systems
● Material UI (Google)
● PatternFly (Red Hat)
● Orbit (Kiwi)
● Ant design
● Bit
Difference between Style guide and Pattern library
8
Style guide x Pattern library
Style guide - focuses on graphic styles (colors,
spacers, icons, content…) and their usage.
Pattern library - integrates functional
components and their usage.
Design system usually contains both.
Architecture
9
Examples
10
Centralized vs. Distributed system
11
Centralized vs. Distributed system
Centralized - one team is in charge of the
system and makes it evolve.
Distributed - several people of several teams
are in charge of the system. The adoption of the
system is quicker because everyone feels
involved.
How do we use PatternFly?
12
Usage
Components as elements
Type styles
Color palette
Template
preview
Show library and template
14
Handoff to developers
15
Usage
16
17
Component lifecycle & optimization
React advanced
React beginner
18
https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
Component lifecycle
● After React dev team introduced hooks, the life cycles of react component
has changed significantly - preparation for concurrent mode and async rendering
● The management is different for React Class and Functional components
React beginner
19
https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
Component lifecycle - Classes
There are several predefined class functions with a static trigger sequence
● constructor
○ Is triggered when the class is instantiated
○ Useful for setting initial component state, registering listeners…
○ In most cases is not really necessary
● componentWillMount (deprecated)
○ After constructor, but before first render
○ Was used for initial data fetch
○ Misuse will cause faulty state changes in async mode
● componentDidMount
○ Is called once only after initial render
○ New place for initial data fetch
React beginner
20
https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
Component lifecycle - Classes
○ componentWillReceiveProps (deprecated)
■ Component is about to receive new props, but it did not re-render
○ componentDidUpdate
■ Props or component internal state were updated
■ Based you can compare new and previous props/state to make some updates,
api calls, logs, etc.
■ Danger of infinite loops
■ State changes must be wrapped in condition
○ componentWillUnmount
■ Clean up phase before the component is removed from virtualDOM
React beginner
21
https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
Component lifecycle - Classes
○ shouldComponentUpdate
■ Rending is the most expensive operation in DOM an any library/framework
■ Developer can use this method to programmatically check whether to trigger render
method or not
■ This will affect component children and not send new props to them
■ If children rely on parent component you cannot use this in most cases
○ Render - main rendering method
■ Must be implemented in every class component and return something renderable
■ Render is triggered on prop and state changes by default
● Can be handled via shouldComponentUpdate
○ componentDidCatch - handler for unpredicted errors in virtual DOM
■ The “Whoops! Something has happened.” screen
React beginner
22
https://reactjs.org/docs/hooks-intro.html
Component lifecycle - functions
You can handle functional component lifecycle via useEffect hook
● Possible in React version 16.8.x and later
● Allows performing side effects in your functions
○ Side effect triggers something outside of a function scope
○ Breaks the pure function rule - same input may give you different output
○ Necessary for efficiently reacting on (user) events
● Can replace all lifecycle methods, except componentDidCatch
React beginner
23
https://reactjs.org/docs/hooks-intro.html
Component lifecycle - functions
useEffect arguments:
● Effect function
● List of triggers (dependencies)
There can be multiple effects, reacting on different triggers.
That way, we can mimic the life cycles of classes.
const Component = ({ username }) => {
useEffect(() => {
API.getUserDataAndUpdateAppGlobalState(`api/…`
return () => {
cleanAppGlobalState()
}
}, [username])
return (
{username}
)
}
React beginner
24
https://reactjs.org/docs/hooks-intro.html
Component lifecycle - functions
● No list of triggers means that the effect will trigger
on every props/state change
○ Will cause infinite loop if state is changed here
○ Same use cases as componentDidUpdate
○ Will also trigger like componentDidMount
● Empty dependencies list means that it will trigger only once, after initial mount
○ componentDidMount
○ Does not react on any props/state updates
useEffect(() => {
/**effect */
})
React beginner
25
https://reactjs.org/docs/hooks-intro.html
Component lifecycle - functions
● Effect will be called when any variable in
the list is changes
○ componentDidUpdate,
componentDidMount
○ Non primitive types must follow immutable pattern to trigger effect -> must
return new instance
○ Also will be triggered in first render
useEffect(() => {
/**effect */
}, [propName, stateName])
React beginner
26
https://reactjs.org/docs/hooks-intro.html
Component lifecycle - functions
● If effect returns a function, it will be
called before component is
unmounted from DOM
● componentWillUnmount
useEffect(() => {
/**effect */
return () => {
/**clean up */
}
}, [propName, stateName])
React beginner
27
Render cycle - when rendering happens
● Render function is triggered when
○ Component props has changed
○ Component state has changed
○ Component context has changed
○ Parent has re-rendered
● Everything can be optimized/block to save rendering cycles
● Render will not trigger if props/state are
MUTATED VARIABLES OF THE SAME INSTANCE
React beginner
28
Different data binding (one vs two way)
● One way data binding
○ Used by all modern UI libraries/frameworks
○ Data can be send only in one direction in the DOM
○ Data is “bubbling” down through nodes to the leaves of the DOM tree
○ Predictable behaviour
○ Forces component independence
○ From parents to children (React)
○ From children to parents (not a good idea)
Although technically parents can access its children data it's not a good idea
■ DO NOT TOUCH CHILDREN!
■ It opens pandora's box of bugs
React beginner
29
Two way data binding
● Used in older libraries/frameworks
● One of the reasons why original Angular was abandoned
● Developers ignored good practices and were accessing parent data from children
● Components lost their independence
const InputComponent = () => {
return (
)
}
React beginner
30
Optimization hooks
● There are several hooks that can help you optimize your code
○ As always, before optimizing, check if you actually need it
● useCallback
○ Used to define a function that has referential equality between renders - changes when
its dependencies change
● useMemo
○ Used to calculate a value that has referential equality between renders - changes
the value when their dependencies change
● useRef
○ Special hook, that behaves similar to useState, but does not trigger re-render
React beginner
31
Additional hooks
● useContext
○ React.provider hook to consume context
○ Easy to use multiple context providers in one component
● useReducer
○ State management hook, if you need to store big chunk of data in component
● Custom hooks
○ You can write your own hooks, and share them in your library
○ Great examples: useDispatch, useSelector from react-redux library
○ Any function can be “hook” as long as it uses any React’s hooks
32
Thinking with redux - one state to rule them all
Redux
33
Agenda
What is redux - principles
Going from action type trough action to state update
How to use connect - 3 parts of connect function
How to use hooks with Redux
Middlewares and other cool tricks
Redux Toolkit
You might not need Redux - useReducer
Let’s do some coding…
Redux basics
34
What is Redux - definition
● A predictable state container for JavaScript applications.
Key concepts:
● State - a single object that represents the application’s state
● Store - single source of truth (object) where the global state of the entire application is stored
○ provides methods: getState(), dispatch(action), subscribe()
● Action - plain objects that describe what should happen
○ must have a type (identifies the action) and can carry payload to change the state
● Reducer - function taking the current state and an action and returning a new state
○ pure function => always returns the same output for the same inputs
● Dispatch - method used to send an action to the reducer which updates the state
● Subscriber - function that gets called every time the state changes
○ React Redux provides higher-level abstractions that take care of it (useSelector, connect)
Redux basics
35
Draw it, and it all makes sense…
1. Something triggers an action - pure
function that returns object
2. Action is dispatched into store
(carrying payload)
3. Reducers pass this action around and
mutate state based on type and payload
4. You can track history of actions because
they are pure functions
Redux basics
36
Going from action type
● Action type - string constant to identify action, kinda like name
export const SOME_ACTION = 'SOME_ACTION_TYPE';
Redux advanced
37
https://github.com/redux-utilities/flux-standard-action
Going from action type trough action
const doSomeAction = (data, entityId) => ({
type: SOME_ACTION,
payload: {
entityId,
data
},
meta: { entityId },
error: false
});
● Action - combined type, payload, error, meta
○ Type - to identify action
○ Payload (optional) - actual data, usually object
○ Meta (optional) - additional data, usually to identify records
○ Error (optional) - boolean value to indicate error
Redux basics
38
Going from action type trough action to state update
● Reducer is function that takes state and action
● Reacts to action and mutates state in expected way
const reducer = (state, action) => {
return {
...state,
entities: state.entities.map(item => ({
...item,
...item.id === action.entityId && action.data
}))
};
};
Redux basics
39
Going from action type trough action to state update and use them
● createStore - the OLD way - to use reducers in a store
○ Reducer function
○ Default state
○ Enhancers
● combineReducers - to namespace your state and split reducers
● applyMiddleware - enhancer function to user middlewares (logger, async functions,etc.)
createStore(
combineReducers({ appState }),
{ appState: {} },
applyMiddleware(logger)
);
Redux basics
40
How to use redux in react app
● Connect function - the OLD way
○ mapStateToProps
○ mapDispatchToProps (optional)
○ mergeProps (optional)
● Hooks
○ useDispatch - provides access to the dispatch function
○ useSelector - allows you to extract data from the state
■ takes a selector that receives the entire store state and
returns the piece of state you need
○ useStore - direct access to the store (actions not tied to
component’s rendering)
Redux basics
41
How to use hooks with redux - useSelector
● Replaces mapStateToProps and mergeProps functions
● Allows to pluck pieces of state from store
● It’s recommended to use multiple selectors in component to improve performance
○ Always try to requests only primitive values, not whole objects (not always possible)
const Component = ({ userId }) => {
const name = useSelector(({ userReducer: { profile: { name } } }) => name);
const email = useSelector(({ userReducer: { profile: { email } } }) => email);
const orders = useSelector(({ orderReducer: { orders } }) => orders.find(order => order.userId === userId));
return (
...
)
}
Redux basics
42
How to use hooks with redux - useDispatch
● Replaces mapDispatchToProps
● Returns a dispatch function from closest store
● Use this function to call redux actions
const Component = () => {
const dispatch = useDispatch()
const handleThemeToggle = themeVariant => dispatch({ type: 'TOGGLE_THEME', payload: themeVariant })
return (
)
}
Redux basics
43
How to use hooks with redux - useStore
● In order to access store
const Component = () => {
const store = useStore();
console.log(store);
return 'FooBar';
}
Redux basics
44
Middlewares and other cool tricks
● As reducer, listens on actions, but catches them before they are passed to reducers
● Can observe, modify action or even prevent it from reaching reducers
● Usually middleware is used to add some side effect to action
type: ‘Foo’
Duplication
middleware
type: ‘New Foo’
type: ‘Foo’ Reducer 1
Reducer 2
Redux basics
45
Redux toolkit
● All in one library
● Heavily opinionated
● Reducers replaced with slices
○ Map of reducers
● API creator - allows you to easily setup endpoints connected to redux
● A lot of abstraction, quite an overkill for small apps, opinionated = less flexibility.
(Jotai - easier and minimalistic, granular state, more flexible, less boilerplate, lightweight)
Redux DevTools
● a browser extension
● useful for debugging application’s state changes
Redux basics
46
You might not need redux - useReducer
● Hook introduced in React version 16.8.0
● Introduces reducers to core React
● Its meant to be used for complex component state updates
○ More than two “setState” calls in one callback
○ Every setState triggers one render always
○ Multiple setState have negative performance impact
● useReducer is here to prevent developers store objects in state (useState)
○ Trigger unnecessary re-renders
● useReducer on its own cannot replace redux
○ Lacks optimizations, middlewares, namespacing, context, etc.
○ Would require additional functions to fully replace redux
○ But at that point, you have implemented redux library
● On its own (with clever context and memo usage ), can replace redux in smaller scale applications
Redux advanced
47
Let’s do some coding
● State vs Redux vs UseReducer -
https://codesandbox.io/s/friendly-lovelace-sf7s59
Redux advanced
48
Homework
● Deploy your application
React beginner
49
Table - let’s write some code
● Deploy application
● Log out
● Table