Actually, you should avoid using this
when using react hooks. It causes side effects. That's why react team create react hooks
.
If you remove codes that tries to bind this
, you can just simply pass setName
of Parent
to Child
and call it in handleChange
. Cleaner code!
function Parent() {
const [Name, setName] = useState("");
return <div> {Name} :
<Child setName={setName} ></Child>
</div>
}
function Child(props) {
const [Name, setName] = useState("");
function handleChange(ele) {
setName(ele.target.value);
props.setName(ele.target.value);
}
return (<div>
<input onChange={handleChange} value={Name}></input>
</div>);
}
Moreover, you don't have to create two copies of Name
(one in Parent
and the other one in Child
). Stick to "Single Source of Truth" principle, Child
doesn't have to own the state Name
but receive it from Parent
. Cleanerer node!
function Parent() {
const [Name, setName] = useState("");
return <div> {Name} :
<Child setName={setName} Name={Name}></Child>
</div>
}
function Child(props) {
function handleChange(ele) {
props.setName(ele.target.value);
}
return (<div>
<input onChange={handleChange} value={props.Name}></input>
</div>);
}