简体   繁体   中英

How to rerender component in useEffect Hook

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.

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:

编辑启发式-rubin-pmdjk

Simplest way

Add a dummy state you can toggle to always initiate a re-render.

const [rerender, setRerender] = useState(false);

useEffect(()=>{

    ...
    setRerender(!rerender);
}, []);

And this will ensure a re-render, since components always re-render on state change.

You can call setRerender(!rerender) anywhere anytime to initiate re-render.

const [state, set] = useState(0);

useEffect(() => {
  fn();
},[state])

function fn() {
  setTimeout((), {
    set(prev => prev + 1)
  }, 3000)
}

The code above will re-render the fn function once every 3 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM