Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks - How do I implement shouldComponentUpdate?

I know you can tell React to skip an effect by passing an array as an optional second argument.

For example:

useEffect(() => {   document.title = `You clicked ${count} times`; }, [count]); // Only re-run the effect if count changes 

But what if i want to control over the comparison? to add my own comparison logic.

I would expect something like React.memo that you can pass a function as a second argument.

like image 989
Idan Dagan Avatar asked Feb 06 '19 10:02

Idan Dagan


People also ask

Why do we use shouldComponentUpdate () function in Reactjs?

Use shouldComponentUpdate() to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.

How do I get past state in React hooks?

While there's currently no React Hook that does this out of the box, you can manually retrieve either the previous state or props from within a functional component by leveraging the useRef , useState , usePrevious , and useEffect Hooks in React.

How do you pass props in React hooks?

In order to pass the isActive prop from the parent (MyCard) to the child (MyButton), we need to add MyButton as a child of MyCard. So let's import MyButton at the top of the file. import MyButton from "./Button"; Then, let's add MyButton as a child in the return statement of MyCard component.


1 Answers

In a comment above Gabriele Petrioli links to the React.memo documentation that explains how to implement shouldComponentUpdate. I was googling combinations of shouldComponentUpdate + useEffect + "react hooks", and this came up as the result. So after solving my problem with the linked documentation I thought I would bring the information here as well.

This is the old way of implementing shouldComponentUpdate:

class MyComponent extends React.Component{   shouldComponentUpdate(nextProps){     return nextProps.value !== this.props.value;   }   render(){     return (      <div>{"My Component " + this.props.value}</div>     );    } } 

The New React Hooks way:

React.memo(function MyComponent (props) {    return <div>{ "My Component " + props.value }</div>;  })  

I know you were probably asking for more in your question, but for anyone coming from Google looking for how to implement shouldComponentUpdate using React Hooks, there you go.

The documentation is here: how-do-i-implement-shouldcomponentupdate

like image 178
PAT-O-MATION Avatar answered Sep 20 '22 13:09

PAT-O-MATION