Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views26 pages

Start Using React 16.8

The document provides an overview of React 16.8 features, particularly focusing on Hooks, which allow developers to use state and other React features without classes. It covers the motivation behind Hooks, their usage, rules, and additional Hooks like useContext, useReducer, useCallback, and useMemo. The document also discusses how to implement these features in projects and includes references for further reading.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views26 pages

Start Using React 16.8

The document provides an overview of React 16.8 features, particularly focusing on Hooks, which allow developers to use state and other React features without classes. It covers the motivation behind Hooks, their usage, rules, and additional Hooks like useContext, useReducer, useCallback, and useMemo. The document also discusses how to implement these features in projects and includes references for further reading.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Shaping the Type here if add

future of digital info needed for


business every slide

React 16.8 in NTA

gft.com 11/12/2019 1
Shaping the Type here if add
future of digital info needed for
business every slide

Disclaimer

This training session is recorded with the purpose of becoming training


material for current or future NTA team members.

This material comes into your possession or knowledge in connection


with the performance services you are providing to DB.

The information herein provided must then be treated as confidential,


and cannot be copied, published or disclosed to any person not having
a legitimate need to know for the purpose of providing services to DB.

gft.com 11/12/2019 2
Shaping the Type here if add
future of digital info needed for
business every slide

1. React 16.8 features in NTA


2. Hooks
▪ Motivation
▪ useState
▪ useEffect
Agenda

▪ Rules of Hooks
▪ Custom hooks
▪ Additional Hooks
▪ Other libraries hooks

3. Hooks in EFX
4. How to start using it in your project
5. References
6. More readings
gft.com 11/12/2019 3
Shaping the Type here if add
future of digital info needed for
business every slide

Features that compete to NTA

▪ Fragments:
▪ Problem: render must always return one parent node, so in the past we need to wrap a list of
components in a div. Which created unnecessary divs in our DOM hierarchy.
▪ Solution: <React.Fragment> surrounds this list of components without creating extra DOM nodes.

BEFORE AFTER
render(){ render(){
<div> <React.Fragment>
<ChildA /> <ChildA />
<ChildB /> <ChildB />
</div> </React.Fragment>
} }

▪ Hooks

gft.com 11/12/2019 4
Shaping the Type here if add
future of digital info needed for
business every slide

Features that compete to NTA

▪ React profiler
▪ React 16.5 adds support for a new DevTools profiler plugin. It collects timing information about each
component that’s rendered in order to identify performance bottlenecks in React applications. […]

gft.com 11/12/2019 5
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks - Motivation

▪ “[…] Hooks let you use more of React’s features without classes.”
It is, we can create React components with functions and still use common React
features that were only possible to use them with React classes.
▪ “Hooks let you split one component into smaller functions based on what pieces are
related (such as setting up a subscription or fetching data), rather than forcing a split
based on lifecycle methods.”
▪ “ […] class components can encourage unintentional patterns that make these
optimizations fall back to a slower path. Classes present issues for today’s tools, too. For
example, classes don’t minify very well, and they make hot reloading flaky and
unreliable.”
▪ “[…] Hooks work side-by-side with existing code so you can adopt them gradually“
▪ “Hooks can cover all use cases for classes while providing more flexibility in
extracting, testing, and reusing code. This is why Hooks represent our vision for the
future of React.” – Dan Abramov

gft.com 11/12/2019 6
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks - useState
Variable for the state

Function to set state


Initial state value

Read state

Update state

gft.com 11/12/2019 7
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks - useEffect

▪ Mindset change: “effects run after


every render, are conceptually a
part of the component output, and
“see” the props and state from that
particular render”
▪ “Inside the scope of a single render,
props and state stay the same. “
▪ Instead of thinking in terms of
“mounting” and “updating”, you
might find it easier to think that
effects happen “after each render”.
React guarantees the DOM has
been updated by the time it runs the
effects.

It can access state variables.

gft.com 11/12/2019 8
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks - useEffect
▪ Effects may also optionally specify how to
“clean up”. The clean up is run just before
executing the effect, in a new render step.
But as mentioned, the cleanup will be done
with state and props of previous effect
version (previous render). This function is
also called when unmounting.
▪ You can use as many effects as you want,
letting you “organize side effects in a
component by what pieces are related,[…],
rather than forcing a split based on lifecycle
methods.”
▪ Unlike componentDidMount or
componentDidUpdate, effects scheduled
with useEffect don’t block the browser from
updating the screen. […] The majority of
effects don’t need to happen synchronously.
[…]

gft.com 11/12/2019 9
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks - useEffect
▪ In some cases, cleaning up or applying the effect after every render might create a performance
problem. In class components, we can solve this by writing an extra comparison with prevProps
or prevState inside componentDidUpdate.
With effects we pass an array argument with a list of dependencies.

▪ If you want to run an effect and clean it up only once (on mount and unmount), you can pass an
empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any
values from props or state, so it never needs to re-run. This isn’t handled as a special case — it
follows directly from how the dependencies array always works.
Be sure of what you are doing when using empty array, if your effect uses state or props, it will
create bugs.

gft.com 11/12/2019 10
Shaping the Type here if add
future of digital info needed for
business every slide

Rules of Hooks

▪ Only Call Hooks at the Top Level: Don’t call Hooks inside loops, conditions, or nested
functions. Instead, always use Hooks at the top level of your React function. By following
this rule, you ensure that Hooks are called in the same order each time a component
renders. That’s what allows React to correctly preserve the state of Hooks between
multiple useState and useEffect calls.
▪ Only Call Hooks from React Functions: Don’t call Hooks from regular JavaScript
functions. Instead, you can:
▪ Call Hooks from React function components.
▪ Call Hooks from custom Hooks.
By following this rule, you ensure that all stateful logic in a component is clearly visible
from its source code.

gft.com 11/12/2019 11
Shaping the Type here if add
future of digital info needed for
business every slide

Custom Hooks

▪ A custom Hook is a JavaScript function whose name starts with ”use” and that
may call other Hooks.
▪ Custom Hooks offer the flexibility of sharing logic that wasn’t possible in React
components before. You can write custom Hooks that cover a wide range of use cases
like form handling, animation, declarative subscriptions, timers, […]
▪ […] you can build Hooks that are just as easy to use as React’s built-in features.

gft.com 11/12/2019 12
Shaping the Type here if add
future of digital info needed for
business every slide

Additional Hooks - useContext

▪ Accepts a context object


(the value returned from
React.createContext)
and returns the current
context value […]. The
current context value is
determined by the value
prop of the nearest
<MyContext.Provider>
above the calling
component in the tree.
▪ When the context
changes, this Hook will
trigger a render.

gft.com 11/12/2019 13
Shaping the Type here if add
future of digital info needed for
business every slide

Additional Hooks - useReducer

▪ […] Accepts a reducer of type


(state, action) => newState,
and returns the current state
paired with a dispatch
method. […]
▪ Instead of reading/setting the
state, it dispatches an action
that encodes the information
about what happened.[…]
▪ You can also access props
from a reducer.
▪ If you return the same value
from a Reducer Hook as the
current state, it won’t render
children or firing effects.

gft.com 11/12/2019 14
Shaping the Type here if add
future of digital info needed for
business every slide

Additional Hooks - useCallback


▪ In case you need to create a function and pass it down to your children as a callback function
in one of your function components, you will find that your children will be render again
because callback function passed as prop will have a new reference.
▪ In order to avoid it you can use useCallback hook.
Dependencies

gft.com 11/12/2019 15
Shaping the Type here if add
future of digital info needed for
business every slide

Additional Hooks - useMemo


▪ Pass a “create” function and an array of dependencies. useMemo will only recompute the
memoized value when one of the dependencies has changed. This optimization helps to
avoid expensive calculations on every render.
▪ […] The function passed to useMemo runs during rendering. Don’t do anything there that you
wouldn’t normally do while rendering. For example, side effects belong in useEffect, not
useMemo.
▪ You may rely on useMemo as a performance optimization, not as a semantic guarantee. In
the future, React may choose to “forget” some previously memoized values and recalculate
them on next render, e.g. to free memory […]. Write your code so that it still works without
useMemo — and then add it to optimize performance.

Dependencies

gft.com 11/12/2019 16
Shaping the Type here if add
future of digital info needed for
business every slide

Additional Hooks - useRef


▪ […] useRef is like a “box” that can hold a mutable value in its .current property
▪ The object returned by useRef is the same in every render.
▪ You can mutate its .current field and read this value in a different effect / render
function Example() { Initial value
const [count, setCount] = useState(0);
const latestCount = useRef(count);

useEffect(() => {
latestCount.current = count;
console.log('setting', latestCount.current);
setTimeout(() => {
console.log(`You clicked ${latestCount.current} times`);
}, 3000);
});

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}

gft.com 11/12/2019 17
Shaping the Type here if add
future of digital info needed for
business every slide

Other libraries Hooks


▪ Lots of other React libraries embraced hooks.
▪ React-redux created
▪ useSelector: Allows you to extract data from the Redux store state, using a selector function.
▪ useDispatch: returns a reference to the dispatch function, so you can dispatch funcions as needed.
▪ …
▪ Styled-components are about to release its version 5 with the first hook: useTheme
▪ React-i18next: useTranslation gets the t function and i18n instance inside your functional
component.
▪ https://usehooks.com/

gft.com 11/12/2019 18
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks in EFX
▪ EFX uses
▪ useState
▪ useEffect
▪ useCallback
▪ useSelector export function OneField({
formik
▪ useContext }) {
▪ useDispatch const lang = useLang();
const t = useSelector(tSelectorScoped)('Efx');
const [ errors, setErrors ] = useState([]);
const handleOnError = useCallback(new_errors => setErrors(new_errors), []);
const currency = useCurrency(formik);
const validate = useCallback((value = '') => {
…….

gft.com 11/12/2019 19
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks in EFX
▪ Custom hook created to get the
language and currency.
import { useContext } from 'react';
import { I18nContext } from 'react-i18next';

export default function useLang() {


const { i18n: { language } } = useContext(I18nContext) || {};
return language;
}

export default function useCurrency(form) {


const currencyName = form.values[CurrencySelect.fieldName];
const currencies = useSelector(selectCurrencies) || [];
const defaultCurrency = {
decimals: 2,
currency: undefined,
minAmount: 1
};
return currencies.filter(({ currency }) => currency === currencyName)[0] || defaultCurrency;
}

gft.com 11/12/2019 20
Shaping the Type here if add
future of digital info needed for
business every slide

Hooks in EFX

Function useCheckLoadData(loadData, checkFunction, deps, handleError){


▪ Custom hook created to fetch data,
dispatch = useDispatch();
t = useSelector(tSelector)(‘errors’);
evaluate the response and optionally
useEffect(() => {
handle errors.
loadData().then(result => {
const error = checkFunction(result);
if(error) dispatch(action);
}).catch(error => {
if (typeof handleError === 'function') {
const errorContent = handleError(error);
dispatch(errorContent);
return;
}
dispatch({type: ERROR, payload: {
text: t('errors.generic.text'),
title: t('errors.generic.title')
}}
);
});
}, deps);

gft.com 11/12/2019 21
Shaping the Type here if add
future of digital info needed for
business every slide

How to start using it in your project


▪ EFX repository is based in the last version of our starter project, which already uses React
16.8, webpack 4 and some new library versions.
▪ If you would like to create a new repository, please use the starter project and you can start
using React 16.8 features.
▪ If you want to migrate an existing project to React 16.8, take a look to the PR where the
starter was updated with React 16.8 version.

gft.com 11/12/2019 22
Shaping the Type here if add
future of digital info needed for
business every slide

Change your mindset


▪ No more clases
▪ Use function components
▪ Do not think when an effect must be run in lifecycle methods but to which data they depend on.

export class ClassComponent extends React.PureComponent { export function CheckData( { propA, propB } ){
constructor(props){...}
useHook(...);
componentWillUnmount() {...}
useHook(...);
componentDidMount(){...}
return (...);
render(){...}
}, prop }

gft.com 11/12/2019 23
Shaping the Type here if add
future of digital info needed for
business every slide

References used in this presentation

▪ https://en.reactjs.org/docs/hooks-intro.html
▪ https://overreacted.io/a-complete-guide-to-useeffect/
▪ https://react-redux.js.org/next/api/hooks
▪ https://www.styled-components.com/releases
▪ https://react.i18next.com/latest/usetranslation-hook
▪ https://es.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html

gft.com 11/12/2019 24
Shaping the Type here if add
future of digital info needed for
business every slide

More readings

▪ https://www.robinwieruch.de/react-hooks-fetch-data
▪ https://wattenberger.com/blog/react-hooks

gft.com 11/12/2019 25
Shaping the future
of digital business
React 16.8 in NTA
GFT IT Consulting S.L.U.
Samuel Tamarit Jaime
Developer
Avinguda Oest, 48
46001 Valencia
T +34 96 301 2686
[email protected]

© 2019 | GFT Technologies SE and its affiliates. All rights reserved.

You might also like