How to rerender component in useEffect Hook

Piotr Żak picture Piotr Żak · Sep 19, 2019 · Viewed 22.1k times · Source

Ok so:

  useEffect(() => {

  }, [props.lang]);

What should I do inside useEffect to rerender component every time with props.lang change?


Solution:

I solve this problem in changing some idea of problem (I use another function to work's well with language change.

Answer

Elder Patten Ferreira picture Elder Patten Ferreira · Sep 20, 2019

Think of your useEffect as a mix of componentDidMount, componentDidUpdate, and componentWillUnmount, as stated in the React documentation.

To behave like componentDidMount, you would need to set your useEffect like this:

  useEffect(() => console.log('mounted'), []);

The first argument is a callback that will be fired based on the second argument, which is an array of values. If any of the values in that second argument change, the callback function you defined inside your useEffect will be fired.

In the example I'm showing, however, I'm passing an empty array as my second argument, and that will never be changed, so the callback function will be called once when the component mounts.

That kind of summarizes useEffect. If instead of an empty value, you have an argument, like in your case:

 useEffect(() => {

  }, [props.lang]);

That means that every time "props.lang" changes, your callback function will be called. The useEffect will not rerender your component really, unless you're managing some state inside that callback function that could fire a re-render.

UPDATE:

If you want to fire a re-render, your render function needs to have a state that you are updating in your useEffect.

For example, in here, the render function starts by showing English as the default language and in my use effect I change that language after 3 seconds, so the render is re-rendered and starts showing "spanish".

function App() {
  const [lang, setLang] = useState("english");

  useEffect(() => {
    setTimeout(() => {
      setLang("spanish");
    }, 3000);
  }, []);

  return (
    <div className="App">
      <h1>Lang:</h1>
      <p>{lang}</p>
    </div>
  );
}

Full code:

Edit heuristic-rubin-pmdjk