for example my component tree structure likes the picture,i want to implement that when i press component B's button (or touchable..), i want to change component A's color or shape. this is terrible when i use only props and useState. you can recommend other external libraries. i have been using redux but not working because when i touch B, A is not re-rendered. can you suggest a way or hooks or libraries?
CodePudding user response:
I'm working on a complex react app too with a similar component tree. I think the Redux approach is relevant.
Touching B should update the redux state Then a useEffect hook placed in component A should take the Redux state as dependency in order to trigger the effect.
Something like that :
(the redux part can differ depending on the version)
const CompB = () => {
function sayHelloToCompA() {
useDispatch(updateReduxState('Hello compA')) // triggers redux action that will update redux state
}
return (
<TouchableOpacity style={styles.button}
onPress={() => sayHelloToCompA()>
<Text>Press me</Text>
</TouchableOpacity>
)
}
Once Redux state is updated, then :
const CompA = () => {
const { messageFromCompB } = useSelector(state => state.yourReduxSlice)
useEffect(() => {
console.log(messageFromCompB)
}, [messageFromCompB]);
return (
...
)
}
CodePudding user response:
You might use any state management library out there (such as Redux or MobX), but in a relatively simple case (in which your state isn't that complex), you can use React.Context whose purpose is precisely to avoid Prop Drilling and allow unrelated trees to share information (as long as this information is provided by a common ancestor).