Upgrade to Pro — share decks privately, control downloads, hide ads and more …

React 16 - All the new and shiny things

Marko Arsić
September 19, 2019

React 16 - All the new and shiny things

This year has been really exciting for React developers. There was rarely a new release that generated so much excitement as React Hooks did. We were all hooked instantly! I will go through almost all hot and interesting topics in React (including Hooks) that made our developer life easier this year. You will learn about all the new features with a practical example in a short live-coding demo and be ready for whatever is coming next.

Marko Arsić

September 19, 2019
Tweet

More Decks by Marko Arsić

Other Decks in Programming

Transcript

  1. React 16.x All the new and shiny things Marko Arsić

    Independent Tech Consultant / Senior software developer / Lecturer
  2. Actively engaged in developing software solutions for the last 9

    years using Java, Kotlin, Objective C / Swift and JavaScript programming languages Marko Arsić Senior software developer Independent Tech Consultant Lecturer [email protected] @mArsic In the local community primarily known as a regular speaker at community meetups, and also as a program coordinator and lecturer at Belgrade Institute of Technology React and React Native software packages are currently my focus https://hypetech.xyz
  3. Since the React team released their 16.x vision, it has

    definitely caught lots of attention
  4. tl;dr React Team We plan to split the rollout of

    new React features into the following milestones: • React v16.3 with new lifecycles and context API • React v16.6 with Suspense for Code Splitting • React 16.8 release with React Hooks • A minor 16.x release with Concurrent Mode • A minor 16.x release with Suspense for Data Fetching
  5. Some of the coolest additions to the collection are Context,

    Hooks, lazy loading, Suspense, and the cache API
  6. Context is designed to share data that can be considered

    “global” for a tree of React components (current authenticated user, theme, or preferred language)
  7. Context lets us pass a value deep into the component

    tree without explicitly threading it through every component Context is primarily used when data needs to be accessible by many components at different nesting levels
  8. // Create a Context const NumberContext = React.createContext() // It

    returns an object with 2 values: // { Provider, Consumer } Context standard way
  9. Context standard way function App() { // Use the Provider

    to make a value available to all children return ( <NumberContext.Provider value={42}> <NumberItem /> </NumberContext.Provider> ) }
  10. Context standard way import NumberContext from './NumberContext' function NumberItem() {

    // Use the Consumer to grab the value from context // Notice this component didn't get any props return ( <NumberContext.Consumer> {value => <div>The number is {value}.</div>} </NumberContext.Consumer> ) }
  11. Code-splitting your app can help you “lazy-load” just the things

    that are currently needed by the user This can dramatically improve the performance of your app
  12. Generic way to ensure that high-priority updates like user input

    don’t get blocked by rendering low-priority updates
  13. React.Suspense can suspend the rendering of our component or components

    until some condition is met ( for example data from an endpoint or a resource is loaded) and until then show a fallback (for-example a spinner)
  14. React.memo(...) is a feature introduced in React v16.6. It works

    similar to React.PureComponent Controls how functional components re-render
  15. You know how React class components can hold state ,

    and function components can’t ?
  16. Now, if you write a function component, and later decide

    that it needs a bit of state, you don’t have to refactor the whole thing into a class Those functions are no longer referred as “stateless function components”
  17. Hooks do not replace classes! They’re just a new tool

    that you can use, if you want to The React team has said that they’ve got no plans to deprecate classes in React, so if you want to keep using them you can
  18. Treat hooks as a nice new feature to use when

    you need them, not the New Best Way There is no need to rewrite old code to use hooks
  19. Only call hooks at the top level of your function

    Don’t put hooks in loops, conditionals, or nested functions. In order for React to keep track of your hooks, the same ones need to be called in the same order every single time 1
  20. Only call hooks from React function components, or from custom

    hooks Don’t call them from outside a component (what would that even do?). Keeping all the calls inside components and custom hooks makes your code easier to follow because all the related logic is grouped together 2
  21. The names of hooks must start with “use”. For example

    useState or useEffect Keep in mind that some names are already taken and reserved by React itself (useState, useEffect, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect, useDebugValue) 3
  22. React 16.8.* is the first release to support Hooks. Current

    React version is 16.9.* When upgrading, don’t forget to update all packages , including React DOM.
  23. The useState hook lets you add state to function components

    By calling useState inside a function component, you’re creating a single piece of state
  24. In classes, the state is always an object. You can

    store properties on that object
  25. With hooks , the state doesn’t have to be an

    object . State can be any type you want – an object, an array, a number, a boolean, a string ...
  26. We need to import the useState hook from React import

    React, { useState } from 'react' // (or write React.useState)
  27. useState returns an array with 2 elements We use ES6

    array destructuring to assign names to them const [clicked, setClicked] = useState(false)
  28. The first element is the current value of the state,

    and the second element is a state setter function const [clicked, setClicked] = useState(false) Call setClicked with a new value, and the state will be set and the component will re-render
  29. import React, { useState } from 'react' const PassengersTracker =

    () => { const [passengers, setPassengers] = useState(0) const increment = () => { setPassengers(passengers => passengers + 1) } return ( <div> We have {passengers} passengers on board! <br /> <button onClick={increment}>+ New passenger</button> </div> ) }
  30. Picture this: You have a perfectly good function component, and

    then one day, you need to add a lifecycle method to it. The useEffect hook can help you here
  31. With useEffect, you can handle lifecycle events directly inside function

    components. componentDidMount componentDidUpdate componentWillUnmount All with one function within a function component!
  32. import React, { useEffect } from 'react' function LifecycleDemo() {

    // It takes a function useEffect(() => { // Called after every render, by default console.log('render!'); // If you want to implement componentWillUnmount, // return a function from useEffect return () => console.log('unmounting...') }) return "I'm a LifecycleDemo component" }
  33. useEffect(() => { return () => console.log('cleanup function...') }) The

    cleanup function you can (optionally) return from useEffect it is not called only when the component is unmounted
  34. Clean up function gets called every time before that effect

    runs – to clean up from the last run This is actually more powerful than the componentWillUnmount lifecycle because it lets you run a side effect before and after every render
  35. useEffect(() => { console.log('render!') return () => console.log('cleaning up...') })

    useEffect runs after every render (by default), and can optionally clean up for itself before it runs again
  36. useEffect it’s a way to run side effects after render

    – including the potential cleanup you’d want to do before each render, and before unmounting
  37. If you want your effects to run less often, you

    can provide a second argument – an array of values . Think of them as the dependencies for that effect.
  38. If one of the dependencies has changed since the last

    time, the effect will run again (It will also still run after the initial render)
  39. const [value, setValue] = useState('initial'); useEffect(() => { // This

    effect uses the `value` variable, // so it "depends on" `value`. console.log(value); }, [value]) // pass `value` as a dependency
  40. Second argument – an array of values, contains every variable

    that the effect function uses from the surrounding scope So if component uses a prop? That goes in the array. If component uses a piece of state? That goes in the array.
  41. Pass the special value of empty array [] as a

    way of saying “only run on mount and unmount” useEffect(() => { console.log('mounted'); return () => console.log('unmounting...'); }, [])
  42. Almost all of new hooks exist to make function components

    as powerful as class Components The useContext hook is a little different It just makes things nicer
  43. The useContext Way // import useContext // (or we can

    write React.useContext) import React, { useContext } from 'react' import NumberContext from './NumberContext' const NumberItem() { const value = useContext(NumberContext) return ( <div>The number is {value}.</div> ) }
  44. Custom hooks are just functions that follow rule (3) After

    that, you can call hooks inside functions. They’re a nice way to roll up a bunch of hooks into one The names of hooks must start with “use”. Their name must be prefixed with “use”. 3
  45. const useToggle = (init = false) => { const [on,

    setOn] = useState(init) const toggle = () => setOn(!on) return [on, toggle] }