I am passing a variable data that is subjected to change from a child component. In the parent component, I am receiving the variable data like this:
<ChildComponent sendDataToParent={sendDataToParent}/>;
let passedVal;
const sendDataToParent = (val) => {
passedVal = val;
};
So I want an alert to be triggered anytime the passed variable changes. So I bind the passed data to a state, and then use useEffect hook. But the useEffect does not trigger anytime the passedValue changes. Though if click the button it shows the changed passed data.
export default function ParentComponet() {
const [isSelected, setIsSelected] = useState(passedVal);
const showPassedData = () => { // This triggers on click of a button
setIsSelected(passedVal);
alert(passedVal)
};
useEffect(() => { // It does not trigger after passedVal changes
setIsSelected(passedVal);
alert(passedVal)
}, [passedVal])
return (
<div>
<Button
onClick={showPassedData}
>
Show Passed Data
</Button>
</div>
);
}
CodePudding user response:
That does not work because React can't detect changes of a normal variable using useEffect
. It can only detect state/props changes. In your case passedVal
is just a variable, even if you change it, it will not trigger useEffect
.
So instead of this
let passedVal;
const sendDataToParent = (val) => {
passedVal = val;
};
you can do this:
const [passedVal, setPassedVal] = useState();
<ChildComponent sendDataToParent={setPassedVal}/>;
CodePudding user response:
sendDataToParent
does not really send data to parent component. If you want to do that you'd need to use smth like Redux or React's context. It's a bit hard to see the complete structure of your components from the code you provided but I think an easier way would be to pass a callback from the parent component to the child, that will be invoked when value changes.
export default function ParentComponent() {
const onDataChange = (val) => {
alert(val)
}
return (
// ...
<ChildComponent onDataChange={onDataChange}/>
)
}