Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  112] [ 1]  / answers: 1 / hits: 22721  / 5 Years ago, wed, may 8, 2019, 12:00:00

How can I pass function with React Hooks? I've used useCallback, but it shows an error that it is not a function.



In class component I was doing it like this:



hidePopUp = (event) => {
event.preventDefault();
this.setState({
popup: !this.state.popup
})
}


Then I was passing function:



<Popup hidePopUp={this.hidePopUp}/>


That's my problem with Hooks:



const hidePopup = useCallback(
(event) => {
event.preventDefault();
setPopup(!popup);
}, []
);

<Popup hidePopup={() => hidePopup}/>


And this is my button in Popup component:



<button onClick={(event)=>this.props.hidePopUp(event)}></button>

More From » reactjs

 Answers
7

First of all spelling mistakes and some common mistakes in passing reference to same function. Otherwise it shouldn't be a problem at all passing the memoized version of this function at all.



Working demo here.



Second, there is no actual use of useCallback being seen here.



You should use a dependency to update your function to represent correct value of popup variable. Here's how:



const togglePopUp = useCallback(
event => {
event.preventDefault();
setPopup(!popup);
},
[popup]
);


Third, when you pass the function as prop, you can pass that directly the reference



<Popup hidePopup={togglePopUp}/>


Note - I've renamed your hidePopUp to togglePopUp


[#52145] Tuesday, April 30, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilianoc

Total Points: 568
Total Questions: 109
Total Answers: 99

Location: Oman
Member since Sat, Jan 7, 2023
1 Year ago
;