0
Hours
0
Minutes
0
Seconds

How to create useWhyDidYouUpdate hook in React.js? | JavaScript Interview Question | Frontend Problem Solving | Custom React Hooks
@Devtools Tech

537

React Hooks are a new addition in React 16.8. They let us use state and other React features without writing a class.

In a React application, components are re-rendered when the props change. Our components might be computationally expensive and we want to minimise the re-renders. We, often, use utilities like React.memo to memoize the components and avoid re-render when props are same between renders. However, despite implementing memoization, components are re-rendered and it is hard to ascertain why it is happening so.

In this question, you need to implement a react custom hook called useWhyDidYouUpdate that prints which props changed between renders on the console and help us better understand & debug our components!

In our example, the component Counter is re-rendering if even it is wrapped using React.memo and count prop doesn't change. Upon switching user, the Counter components re-renders. The hook useWhyDidYouUpdate should be able to tell us which props are causing this isue.

Syntax

...
const Counter = (props) => {
    useWhyDidYouUpdate(componentName, props);
    ...
}

Parameters

  • componentName: name of the component we want debug
  • props: current component's props

Expected Behaviour

Prints all the props on the console that were changed between renders.

Submission

Start the timer and try to complete the solution within 45 mins and share it on LinkedIn & Twitter and tag @devtoolstech @yomeshgupta