React patterns & hooks
 Inheritance
 Composition
React architectural methodologies
 Those familiar with Object Oriented Programming are well aware of Inheritance and use it on a
regular basis. When a child class derives properties from it’s parent class, we call it
inheritance. There are variety of use-cases where inheritance can be useful.
 Example: A car is a vehicle can be modeled with inheritance.
Inheritance
Inheritance(contd.)
 it describes a class that can reference one or more objects of another class as instances.
 Example: A car has an engine can be modeled with composition.
Composition
Composition
(contd.)
 Mixins
 Render Props
 HOC - Higher order component (container)
React patterns
Mixins
 Was introduced in 2015
 Similar to HOCs
 Syntax: React.createClass()
 Motivation:
- Code Reuse and Sharing logic
 Cons:
- Not with ES6 class but only ES5
Mixins (examples)
Mixins (Deprecated)
 Mixins are dead
- ref: https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-
components-94a0d2f9e750
Render Prop
Render Prop: Example
Render Prop(why to use)
 Motivation:
- Reuse code across components when using ES6 classes.
- The lowest level of indirection - it’s clear which component is called and the state
is isolated.
- No naming collision issues for props, state and class methods.
- No hoisting static methods.
Render Prop(why not to use)
 Problems:
- Caution using shouldComponentUpdate as the render prop might close over
data which is unaware of
- May cause minor memory problems when defining a closure for every render
(profiling in dev tools)
- May lead to callback hell dilemma as it can be chain of nested functions inside
each other
- renderProps callback is not so neat as it needs to be wrapped in expression
Render Prop(callback hell)
Render Prop(Profiling)
Render Prop(Libraries)
 Libraries Using renderProps:
- constate https://github.com/diegohaz/constate
- query renderer https://relay.dev/docs/en/query-renderer.html
- downshift https://github.com/downshift-js/downshift
HOC(Example)
 Function that takes another function as a parameter and returns third one
HOC(Example)
 Motivation:
- Reuse code using ES6 classes
- It is easy to make small reusable units of code, thereby supporting the single
responsibility principle.
- Apply multiple HOCs to one component by composing them. The readability can
be improve using a compose function like in Recompose.
HOC(Example)
HOC vs RenderProp
 Motivation:
- HOC better to compose over render props, especially when many cross-cutting
concerns are applied to a component. Many nested render prop components will look
similar to “callback hell”
HOC(Contd.)
 Downsides of HOC and mixins:
- boilerplate code with HOC function name
- It is easy to compose several HOCs together and then this creates a deeply
nested tree making it difficult to debug.
HOC(Contd.)
HOC(Contd.)
HOC(Contd.)
 Downsides of HOC:
- Despite ugly nesting tree, it is also hard to reference an element in HOC’s nested
tree except with react newly adopted forwardRef
React hooks
Hooks(Intro)
 Overview:
- React needs a better primitive for sharing stateful logic.
- functional stateful components
- avoiding class issues (this scoping & constructor issues)
- Hooks allow you to reuse stateful logic without changing your component
hierarchy
- render props and higher-order components that try to solve this. But these
patterns require you to restructure your components when you use them
Hooks(Contd.)
 Plan:
- 100% backwards-compatible. Hooks don’t contain any breaking changes.
- Hooks provide a more direct API to the React concepts you already know: props,
state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful
way to combine them.
- Do not refactor old code but start hooks with new code.
Hooks(Contd.)
 Separation Motivation:
- Complex components become hard to understand so, what?
Of Course, Splitting
Hooks(Contd.)
 Separation Motivation:
-
For example, components might perform some data fetching in and . However,
the same componentDidMountmethod might also contain some unrelated logic that sets up
event listeners, with cleanup performed in componentWillUnmount. Mutually related code that
changes together gets split apart, but completely unrelated code ends up combined in a single method.
This makes it too easy to introduce bugs and inconsistencies.
Hooks(Contd.)
 Classes Motivation:
- Optimization:
For example, classes don’t minify very well, and they make hot reloading
flaky
State Hook
Multiple State Vars
UseEffect Hook
 UseEffect in class:
- Runs on every render cycle
- Similar to componentDidMount and ComponentWillUnmount and
ComponentDidUpdate
UseEffect Hook
UseEffect Hook With API
UseEffect Hook Delegate in class
component
UseEffect Hook Delegate in class
component
 Note
- It cleans up the previous effects before applying the next effects. To illustrate
this, here is a sequence of subscribe and unsubscribe calls that this component could
produce over time
UseEffect Hook Delegate in class
component (Example)
UseEffect Hook Delegate in class
component
 Note
- Forgetting to handle componentDidUpdate properly is a common source of bugs
in React applications.
- So how hooks acts on this! Let us see
UseEffect Hook With API
(Performance Consideration)
 Performance optimization:
- In this example, React would unsubscribe from our ChatAPI when the component unmounts,
as well as before re-running the effect due to a subsequent render
(If you want, there’s a way to tell React to skip re-subscribing if the props.friend.id we passed to
ChatAPI didn’t change.)
UseEffect Hook With API
(Performance Consideration)
In this example, React would unsubscribe from our ChatAPI when the component unmounts,
as well as before re-running the effect due to a subsequent render
(If you want, there’s a way to tell React to skip re-subscribing if the props.friend.id we passed to
ChatAPI didn’t change.)
UseEffect Hook With API
(Performance Consideration)
UseEffect (rendering once)
UseEffect Hook With API
(Performance Consideration)
UseCallback hook
 Memoization:
- Memoized callbacks
UseCallback hook
UseCallback Hook
 Memoization:
-
-
Pass an inline callback and an array of dependencies. useCallback will return a memoized version of
the callback that only changes if one of the dependencies has changed.
This is useful when passing callbacks to optimized child components that rely on reference equality
to prevent unnecessary renders (e.g. shouldComponentUpdate).
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
Update state with complex logic
 userReducer Hook:
- manage complex state update logic
- manage state if separates on previous state
- separation of concerns
userReducer (contd.)
Delegate to instance variables
(useRef)
 useRef Hook:
- instance varaiables in class are useRef in hooks
- mutable varaiables that changes over time
- avoiding unneeded hook rerender
useRef (Example)
Classes to hooks
Rules of using hooks
 Rules:
- Do not use hooks inside loops or conditions – this ensures the state of this
hook between multiple useState and useEffect calls
- Do not call hooks inside regular Js function
- Call hook from functional component
- Call hook from custom hook
References
 References:
- https://programmingwithmosh.com/react/react-composition-vs-inheritance/
- https://programmingwithmosh.com/javascript/react-lifecycle-methods/
- https://reactpatterns.com/
- https://www.richardkotze.com/coding/understanding-render-props-react-js
- https://www.richardkotze.com/coding/hoc-vs-render-props-react
- https://cdb.reacttraining.com/react-inline-functions-and-performance-
bdff784f5578
 References:
- https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce => treasure
HOC: hoisting static methods https://medium.com/@peterpme/learning-higher-order-
components-in-react-by-building-a-loading-screen-9f705b89f569
- https://egghead.io/lessons/react-handle-static-properties-properly-with-higher-
order-components
- https://github.com/facebookincubator/redux-react-hook => using redux with
hooks
- https://blog.logrocket.com/how-to-migrate-from-hocs-to-hooks-d0f7675fd600
- https://reactjs.org/docs/hooks-rules.html
- https://reactjs.org/docs/hooks-custom.html => custom hooks
- https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-
shouldcomponentupdate
References (contd.)
Rules of using hooks
Questions !!

React hooks

  • 1.
  • 2.
     Inheritance  Composition Reactarchitectural methodologies
  • 3.
     Those familiarwith Object Oriented Programming are well aware of Inheritance and use it on a regular basis. When a child class derives properties from it’s parent class, we call it inheritance. There are variety of use-cases where inheritance can be useful.  Example: A car is a vehicle can be modeled with inheritance. Inheritance
  • 4.
  • 5.
     it describesa class that can reference one or more objects of another class as instances.  Example: A car has an engine can be modeled with composition. Composition
  • 6.
  • 7.
     Mixins  RenderProps  HOC - Higher order component (container) React patterns
  • 8.
    Mixins  Was introducedin 2015  Similar to HOCs  Syntax: React.createClass()  Motivation: - Code Reuse and Sharing logic  Cons: - Not with ES6 class but only ES5
  • 9.
  • 10.
    Mixins (Deprecated)  Mixinsare dead - ref: https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order- components-94a0d2f9e750
  • 11.
  • 12.
  • 13.
    Render Prop(why touse)  Motivation: - Reuse code across components when using ES6 classes. - The lowest level of indirection - it’s clear which component is called and the state is isolated. - No naming collision issues for props, state and class methods. - No hoisting static methods.
  • 14.
    Render Prop(why notto use)  Problems: - Caution using shouldComponentUpdate as the render prop might close over data which is unaware of - May cause minor memory problems when defining a closure for every render (profiling in dev tools) - May lead to callback hell dilemma as it can be chain of nested functions inside each other - renderProps callback is not so neat as it needs to be wrapped in expression
  • 15.
  • 16.
  • 17.
    Render Prop(Libraries)  LibrariesUsing renderProps: - constate https://github.com/diegohaz/constate - query renderer https://relay.dev/docs/en/query-renderer.html - downshift https://github.com/downshift-js/downshift
  • 18.
    HOC(Example)  Function thattakes another function as a parameter and returns third one
  • 19.
    HOC(Example)  Motivation: - Reusecode using ES6 classes - It is easy to make small reusable units of code, thereby supporting the single responsibility principle. - Apply multiple HOCs to one component by composing them. The readability can be improve using a compose function like in Recompose.
  • 20.
  • 21.
    HOC vs RenderProp Motivation: - HOC better to compose over render props, especially when many cross-cutting concerns are applied to a component. Many nested render prop components will look similar to “callback hell”
  • 22.
    HOC(Contd.)  Downsides ofHOC and mixins: - boilerplate code with HOC function name - It is easy to compose several HOCs together and then this creates a deeply nested tree making it difficult to debug.
  • 23.
  • 24.
  • 25.
    HOC(Contd.)  Downsides ofHOC: - Despite ugly nesting tree, it is also hard to reference an element in HOC’s nested tree except with react newly adopted forwardRef
  • 26.
  • 27.
    Hooks(Intro)  Overview: - Reactneeds a better primitive for sharing stateful logic. - functional stateful components - avoiding class issues (this scoping & constructor issues) - Hooks allow you to reuse stateful logic without changing your component hierarchy - render props and higher-order components that try to solve this. But these patterns require you to restructure your components when you use them
  • 28.
    Hooks(Contd.)  Plan: - 100%backwards-compatible. Hooks don’t contain any breaking changes. - Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful way to combine them. - Do not refactor old code but start hooks with new code.
  • 29.
    Hooks(Contd.)  Separation Motivation: -Complex components become hard to understand so, what? Of Course, Splitting
  • 30.
    Hooks(Contd.)  Separation Motivation: - Forexample, components might perform some data fetching in and . However, the same componentDidMountmethod might also contain some unrelated logic that sets up event listeners, with cleanup performed in componentWillUnmount. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
  • 31.
    Hooks(Contd.)  Classes Motivation: -Optimization: For example, classes don’t minify very well, and they make hot reloading flaky
  • 32.
  • 33.
  • 34.
    UseEffect Hook  UseEffectin class: - Runs on every render cycle - Similar to componentDidMount and ComponentWillUnmount and ComponentDidUpdate
  • 35.
  • 36.
  • 37.
    UseEffect Hook Delegatein class component
  • 38.
    UseEffect Hook Delegatein class component  Note - It cleans up the previous effects before applying the next effects. To illustrate this, here is a sequence of subscribe and unsubscribe calls that this component could produce over time
  • 39.
    UseEffect Hook Delegatein class component (Example)
  • 40.
    UseEffect Hook Delegatein class component  Note - Forgetting to handle componentDidUpdate properly is a common source of bugs in React applications. - So how hooks acts on this! Let us see
  • 41.
    UseEffect Hook WithAPI (Performance Consideration)  Performance optimization: - In this example, React would unsubscribe from our ChatAPI when the component unmounts, as well as before re-running the effect due to a subsequent render (If you want, there’s a way to tell React to skip re-subscribing if the props.friend.id we passed to ChatAPI didn’t change.)
  • 42.
    UseEffect Hook WithAPI (Performance Consideration) In this example, React would unsubscribe from our ChatAPI when the component unmounts, as well as before re-running the effect due to a subsequent render (If you want, there’s a way to tell React to skip re-subscribing if the props.friend.id we passed to ChatAPI didn’t change.)
  • 43.
    UseEffect Hook WithAPI (Performance Consideration)
  • 44.
  • 45.
    UseEffect Hook WithAPI (Performance Consideration)
  • 46.
  • 47.
  • 48.
    UseCallback Hook  Memoization: - - Passan inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate). useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
  • 49.
    Update state withcomplex logic  userReducer Hook: - manage complex state update logic - manage state if separates on previous state - separation of concerns
  • 50.
  • 51.
    Delegate to instancevariables (useRef)  useRef Hook: - instance varaiables in class are useRef in hooks - mutable varaiables that changes over time - avoiding unneeded hook rerender
  • 52.
  • 53.
  • 54.
    Rules of usinghooks  Rules: - Do not use hooks inside loops or conditions – this ensures the state of this hook between multiple useState and useEffect calls - Do not call hooks inside regular Js function - Call hook from functional component - Call hook from custom hook
  • 55.
    References  References: - https://programmingwithmosh.com/react/react-composition-vs-inheritance/ -https://programmingwithmosh.com/javascript/react-lifecycle-methods/ - https://reactpatterns.com/ - https://www.richardkotze.com/coding/understanding-render-props-react-js - https://www.richardkotze.com/coding/hoc-vs-render-props-react - https://cdb.reacttraining.com/react-inline-functions-and-performance- bdff784f5578
  • 56.
     References: - https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce=> treasure HOC: hoisting static methods https://medium.com/@peterpme/learning-higher-order- components-in-react-by-building-a-loading-screen-9f705b89f569 - https://egghead.io/lessons/react-handle-static-properties-properly-with-higher- order-components - https://github.com/facebookincubator/redux-react-hook => using redux with hooks - https://blog.logrocket.com/how-to-migrate-from-hocs-to-hooks-d0f7675fd600 - https://reactjs.org/docs/hooks-rules.html - https://reactjs.org/docs/hooks-custom.html => custom hooks - https://reactjs.org/docs/hooks-faq.html#how-do-i-implement- shouldcomponentupdate References (contd.)
  • 57.
    Rules of usinghooks Questions !!