React Is Simple [Part-3]

Raghavendra Nk
6 min readMay 30, 2021

Continued part of “React Is Simple”. In this section, we will see some of the life cycle methods and hooks.

1. React Lifecycle

What? Life cycle methods are the functions that will execute based on the phase of the component.

1. render(): To display elements on the screen.
2. constructor(props): Typically called before mounting and used for initializing “state”, binding an “event handler” and creating a “ref” to an instance.
3. componentDidMount(): is invoked immediately after a component is mounted. Best place to make API calls.
4. componentDidUpdate(): is invoked immediately after updating occurs. Best place to update data UI, based on props or state changes.
5. shouldComponentUpdate: return true/false based on this the UI re-render will happen if it's true. Else UI will not refresh. Best place to apply conditions here and return a boolean value, to take control over the UI unnecessary renders. An alternative we can use “PureComponent” which does the same functionality.
6. componentWillUnMount(): is invoked immediately before a component is destroyed. Best place to run clean-up logic.
7. getSnapshotBeforeUpdate(): is invoked right before the most recently rendered output is committed. Any value returned by this lifecycle method will be passed as a parameter to componentDidUpdate().
8. static getDerivedStateFromProps: is invoked before calling the render method. It should return an object to update the state, else return null to update nothing.

How? Below are some examples we can see how we can use these functions and the advantages them.

Error Handling and Boundaries:

What? The ErrorBoundary components that catch Javascript error anywhere in their Child components tree, log those errors and display a fallback UI.

How? In the below example we can see whenever the app goes offline the Child Component is going to throw the error, and this error is captured in the parent to show the fallback UI. By this, the UI will not break with ugly errors!.

Note: ErrorBoundaries can catch child component tree errors, not his own errors. ErrorBoundaries do not catch errors inside event handlers, so better you can use try/catch there.

2. HOC

What? A Higher-Order Component is a function that takes a component & returns a new component.

How? In the below example we can see a Higher-Order component is created, where we are calling the API endpoint to get the data bypassing the Children Component and path string. By this, we need not, again and again, write a code for calling the API and updating them into UI. So we can use this HOC anywhere to make the same functionality.

3. Hooks

Rules of Hooks:

  • Only call hooks at top-level
  • Only call hooks from react functions
  • Don't call hooks inside loops, conditions, or nested functions

Refs and DOM:

What? Refs allow us to access DOM nodes or react elements. Forward-Ref: by using forwardRef we can pass “ref” automatically to one of its children.

Memo/useMemo/PureComponent/Shouldcomponentupdate

Why? There are two problems that useMemo seeks to address:

  • referential equality
  • computationally expensive operations

What and How? Memoization is an optimization technique that passes a complex function to be memorized. In memoization, the result is “remembered” when the same parameters are passed in subsequently.

Note: If you implement useMemo too often in an application, it can harm the performance.
Alternatively, we can achieve this by using the Purecomponent & shouldComponentUpdate.

Here in the above examples we can see the committed, start times along with the time taken for the actual and base duration.

useCallback:

What? The useCallback hook is similar to useMemo, but it returns a memoized function, while useMemo has a function that returns a value.

Context:

Why? Context provides a way to pass data through the component tree without having to pass props down manually at every level.

How? In the below example we are passing the string value from parent component to -> nth component, as context using ‘CreateContext’ and passed using ‘Provider’, and this value can be consumed in the functional component using ‘useContext’ and in class-based component, we can consume the value using ‘Consumer’.

useDebugValue & Custom hook:

Why? Used to display a label for custom hooks in React Devtools.

How? In the below example we can see, we created a custom hook to maintain a flag and that flag is passed as a value in the component, and it can update the value. And “Custom Hook or Not” will be displayed in the react-dev tools by that we can debug the custom hooks easily.

useEffect & useState:

What? useState is used to hold the values which are frequent changes in state variables to update in the UI, same as the this.state= {} object in the class-based component. useEffect is used as an effect to update the state variables or to make API calls, or for some logic to execute in different stages.

When? Fires the effect after every completed render.

How? useEffect can be used as dismount, didupdate and unmount to clean-up

Used as lazy initialize the state based on some calculations. Acts like didupdate whenever the props changes make some complex logic to update state variable.

Note: React will always flush previous renders effect before starting a new update. useEffect vs useLayoutEffect: The difference between the useEffect hook and useLayoutEffect hook is in the timing of their invocation. useEffect hook is invoked after the DOM is painted. useLayoutEffect hook on the other hand is invoked synchronously before changes are painted on the screen.

useReducer: This hook we can use for organized way instead of keeping ’n’ number of state variables in un-organized way.

For more info and advanced level with MERN checkout: https://raghavendrank.medium.com/reactapp-typescript-with-tdd-and-bdd-jest-enzyme-sinon-and-cypress-linting-and-pre-commit-2ae549ca815

Find Out examples here: https://github.com/RaghavendraNK/react-is-simple

Thanks,

--

--

Raghavendra Nk

Full stack developer, interested in building web apps and mobile apps. And sharing the knowledge.