For the people who are using React with Kotlin/JS,...
# javascript
g
For the people who are using React with Kotlin/JS, how do you pass functions to child components, like with the onClick attribute? I read the article below about issues with passing lambdas defined in the render method as props because it creates a new instance of the lambda each time the render method is called, so what is the technique you all use to get past that? https://discuss.kotlinlang.org/t/react-in-kotlin-js-what-i-learned-long-but-useful-read/16168
z
Before I started using hooks and functional components, the technique in the article seemed to work. Essentially, just declaring them as a
val
and assigning a lambda. However, I would recommend looking at hooks and the
useReducer
hook combined with the
useContext
hook, especially if you are thinking about using redux in your project at some point in time.
g
Thanks, I just took a look at those. Perhaps I don't understand how you're using them, but looking at their documentation it looks like they wouldn't help. In the useReducer documentation (https://reactjs.org/docs/hooks-reference.html#usereducer) they run into the exact same problem with the arrow functions getting recreated on each call.
Looks like the
useCallback
hook was created exactly for the purpose I am describing. https://reactjs.org/docs/hooks-reference.html#usecallback
z
Well, in the case of
useReducer
it returns a dispatch function which you can then use to dispatch actions that can process the state and generate a new state. This essentially eliminates the traditional callback mechanism and it doesn't need to generate lambdas. I've been meaning to write up a blog post explaining it from the Kotlin perspective, time is high demand around here though. The
useEffect
hook is also extremely useful for dispatching HTTP requests, which you can then use the dispatcher from the
useReducer
hook to update your component's state. Also, keep in mind you can even write your own hooks.
However, since you are passing functions to child components, it might make sense to create a context to share state between them if they are always used together.
214 Views