I had an issue getting a component to update when it´s props changed. I got it to work using useEffect, but am unsure if it is the correct way to solve my problem.
This is my code:
import * as React from "react";
import "./styles.css";
const InputWithDefaultValue = (props: any) => {
const { value } = props;
//had to add this to get my component to rerender when the button in App-Component was pressed
React.useEffect(() => {
setText(value);
}, [value]);
const [text, setText] = React.useState(value);
return (
<input
value={text}
onChange={(e) => setText(e.currentTarget.value)}
></input>
);
};
export const App = () => {
const [value, setValue] = React.useState("Foo");
return (
<div className="App">
<InputWithDefaultValue value={value} />
<button onClick={() => setValue(Math.random().toString())}>Update</button>
</div>
);
};
export default App;
I was thinking when I updated the props of InputWithDefaultValue it would get rerendered. Is using useEffect to get the component to rerender the correct way to solve the problem or did I find some hacky-solution?
Thanks!