简体   繁体   中英

How to prevent re-render with state update in REACT hook?

(I hope you understand what I want to say although I am not good at English.)

Hello. I migrate code which is written class component to function component. But I have faced several problems like this:

  1. I found no way for migrating shouldComponentUpdate lifecycle. I know React.memo can handle it like shouldComponentUpdate. But this way only can be applied on props update. I need this process on state update.

  2. When you want to change a few state at once, what do you do for it? How can I migrate this code to function component?

    class sample: this.setState({aaa: 'a', bbb: 'b', ccc: 1});

    => Do you just call all method?

    migration example: setAaa(); setBbb(); setCcc(); setAaa(); setBbb(); setCcc();

  3. I don't know how to add callback function with useState.

    class sample: this.setState({state: value}, ()=> {callback function});

    migration exmple: (not solved)

Here is sample code that is similar to my code that should be migrated.

https://codesandbox.io/s/heuristic-firefly-sq1dm9?file=/src/App.js

I can't attach real code because of security, so I just tried to put all problem that I should solve.

Thank you :)

useEffect(() => {
// do stuff here

}, [someState]) // will be triggered only when someState changes

useEffect(() => {
// do stuff here

}, []) // will be triggered once on first render

useEffect(() => {
// do stuff here

}) // will be triggered on each render

useEffect(() => {
// do stuff here
const timer = setTimeout(() => console.log('hi'), 5000)
return () => clearTimeout(timer); // you can unsubscribe of any 
// listeners here
}, []) // will be triggered once on first render

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM