Home > Enterprise >  useEffect doesn't reload child component when its state changes
useEffect doesn't reload child component when its state changes

Time:09-11

I have a react component structure like this:

enter image description here

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?

CodePudding user response:

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.

CodePudding user response:

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 ... />
 )  
}
  • Related