user1189352
user1189352

Reputation: 3885

Why won't my component detect a props change?

I feel like I'm doing everything right? It seems so simple i feel like I'm missing something. Appreciate any help thank you

function App() {
  let jsonData = "a saved page from the database";

  return (
    <div className="App">
      <button onClick={() => {
        jsonData = "a different saved page from the database";        
      }}>
        Change jsonData
      </button>
      <Touchscreen
        key={jsonData}  // something i tried but still doesn't work
        jsonData={jsonData}
      />
    </div>
  );
}

export const Touchscreen = (props) => {  
  React.useEffect(() => {    
    console.log('jsonData: ', props.jsonData);  // won't trigger
  }, [props.jsonData]);

  return (
    <div>
      <span>{props.jsonData}</span>  // never re-renders
    </div>
  );
}

Upvotes: 0

Views: 60

Answers (2)

user10918789
user10918789

Reputation:

You need to put your jsonData as a property of the component state and then use setState to change the value. Calling setState will cause the component to re-render.

For more information about setState, take a look at the docs.

Upvotes: 2

Asaf Aviv
Asaf Aviv

Reputation: 11810

The component redeclaresjsonData on every re-render, you can't preserve the changes on re-renders. if you want to preserve something through the component lifecycle, state is the place for it

function App() {
  const [jsonData, setJsonData] = useState("a saved page from the database");

  return (
    <div className="App">
      <button onClick={() => {
        setJsonData("a different saved page from the database");        
      }}>
        Change jsonData
      </button>
    </div>
  );
}

Upvotes: 4

Related Questions