I have a react component structure like this:
In my table component, I have an option to trigger a modal that prompts user to give some input, which will then send a put request to the backend. In code it looks something like this:
const ParentContainer = (): JSX.Element => {
const dataToPassDown = useSelector((state:IRootState) => selectData(state));
return (
<ParentComponent data={dataToPassDown}/>
)
}
const ParentComponent = (props): JSX.Element => {
const {data} = props;
return (
<MyHeader data = {data}/>
<MyTable data = {data.tableData} />
)
}
const MyTable = (props): JSX.Element => {
const {data} = props;
const [inputFromModal, setInputFromModal] = useState("");
const dispatch = useDispatch();
useEffect(() => {
dispatch(putRequest(inputFromModal);
}, [inputFromModal]);
return (
<Modal visible={false} updateInputValue={setInputFromModal}/>
<Table ... />
)
}
I want to refresh (only) the table component once the modal closes, but in this current setup, useEffect
doesn't reload the table component when its state ( inputFromModal
) changes. Was I wrong in thinking that useEffect
would reload the component when the state changed?
It is not part of useEffect
to re-render your component. component will re-render when its state is changing or Parent component re-render.
By using useEffect
, you tell React that your component needs to do something after render. (or in this case after every change of inputFromModal
. it means that you are making put request every time inputFromModal
is being changed.
For conclusion, in order to re-render your component, you need the data props to be updated by parent component.
You missed one point here, your table will be re-render only when the parent components re-render or the state of your MyTable Component changes , now the data which you are taking from props, set it in your state so that whenever that data changes your component will re-render
const MyTable = (props): JSX.Element => {
const {data} = props;
const [inputFromModal, setInputFromModal] = useState("");
const [tableData, setTableData] = useState();
const dispatch = useDispatch();
useEffect(() => {
setTableData(data)
}, [data]);
useEffect(() => {
dispatch(putRequest(inputFromModal);
}, [inputFromModal]);
return (
<Modal visible={false} updateInputValue={setInputFromModal}/>
<Table ... />
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.