Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react.js React.UseEffect only rendered once upon page load but not when prop changes

I am trying to update my component everytime the prop changes:

export default function ChatMessages(props) {
  const [chatRooms, setChatRooms] = React.useState([]);
  React.useEffect(() => {
    (async () => {
      var x = await GetMessages(props.statePassDown);
      console.log(x);
      setChatRooms(x);
    })();
  }, []);

  return (
    <div class="mainChatView">
      <div>{props.statePassDown}</div>
      {chatRooms.map((chatRoom, index) => {
        return (
          <ul>
            <li key={index}>
              <table>
                <tr>
                  <td>
                    chatID: {chatRoom.chatID}
                    <br></br>
                    message: {chatRoom.message}
                  </td>
                </tr>
              </table>
            </li>
          </ul>
        );
      })}
    </div>
  );
}

But unfortunatley, this code is only ever called once.
I can see that the prop changes through this div:

<div>{props.statePassDown}</div>

This line rerenderes everytime a button is pressed inside another component, but the whole mapping function isnt.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I alter my code that it responds to the change in props.statePassDown?

>Solution :

You’re explicitly setting the effect to have no dependencies:

React.useEffect(()=>{
  // ...
}, []);  // <-- empty dependencies

That means it will only ever be executed on component mount. (If you don’t pass any dependency array, then the effect is executed after each component update.)

Change the dependencies to have the effect be executed when those values change.

React.useEffect(()=>{
  // ...
}, [props.statePassDown]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading