简体   繁体   中英

How to use React.usecallback?

i have a function like below to be called on button click using react and typescript.

function Parent () {
    const [isOpen, setIsOpen] = React.useState(false);
    const handleClick = () => {
        setIsOpen(open => !open);
    }
    return (
        <button onClick={handleClick}>click me </button> 
    );

}

How can i rewrite handleClick method using React.usecallback method?

could someone help me with this. thanks.

We just wrap the functional and add our isOpen to the list of dependent variables, since it will change every click time.

const handleClick = React.useCallback(() => {
  setIsOpen(open => !open);
}, [isOpen]);

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