Reputation: 31
I have a piece of code: App.js
import React, { useState} from 'react';
import Input from './Components/Input';
export default function App() {
const [state,setState]=useState(0);
const handler=()=>{
setState(prev=>prev+1);
}
return <>
<Input></Input>
<button onClick={handler}>Change state</button>
<p>{state}</p>
</>
}
and Input.js:
export default function Input()
{
return <input type="text"></input>
}
The problem is that on changing the state by clicking on the button the Input is not re-rendering while it should as the parent is re-rendering and I know for a fact that children re-render even if their props don't change when parent re-renders. It keeps the value that I type in the input and does not re-render. Same is the case when I use <input type="text">
or <Input prop="dummyProp"></Input>
instead of <Input></Input>
.I am not using strict mode.
Upvotes: 0
Views: 625
Reputation: 673
You have to pass the state as a param to the component
import React , { useState} from 'react';
function Input({ state })
{
return <input type="text" value={state}></input>
}
export function App(props) {
const [state,setState]=useState(0);
const handler=()=>{
setState(prev=>prev+1);
}
return <>
<Input state={state}></Input>
<button onClick={handler}>Change state</button>
<p>{state}</p>
</>
}
Upvotes: 1