Skip to content
Advertisement

Do I need to use useEffect to rerender a component?

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!

Advertisement

Answer

Your solution is correct.

When you add state to a component (i.e. with useState) then the component will no longer automatically update when its props change. Rather, you’d have to use an effect and update an internal state, exactly as you have in your code.

Here’s a related question: React.useState does not reload state from props

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement