Passing a function between multiple react native components

Viewed 29

I am a beginner React Native Developer working on a project with the following structure of components enter image description here

The problem I am having is that I have buttons located in the footer component that needs to call a function located in component 2. I'm just wondering what would be the best way to handle this situation. My first instinct would be to move the function to Page and then pass it down to Footer and Component 2 but from a readability perspective it makes it very unclear what the function itself is doing, and as this is code someone else has written I'm unsure if I would want to make such dramatic changes to the code.

1 Answers

You could create a Context with a memoized function with useCallback and wrap with yout context provider

Then you could import that context in whatever component inside Page

like

import {createContext,useCallback} from 'react'

const myContext = createContext(()=>{})

const {Provider} = myContext

const AppWrapper = ({children}) =>{
const myFunction = useCallback(()=>{
// do something
}, [])


return (
<Provider value={myFunction}>
{children}
</Provider>
)
}

// in your app file
<AppWrapper>
  <App/>
</AppWrapper>

Now you can use your function in whereever component inside Page lik

import {useContext} from 'react'

const MyComponent = () =>{
const myFunction = useContext(myContext)

return <>...</>
}
Related