1
votes

Perhaps I got a wrong understanding of react flow, but can someone explain this magic :)

Why I have to update inner state through the useEffect hook in React?

I thought the component updating will trigger rewriting the initial state of useState hook.

  const [list, setList] = useState<TabItem[]>(tabs);

  useEffect(() => {
    setList(tabs);
  }, [tabs]);

1
What is "inner state"? The initial state is only referenced once when state is instantiated, separate from everything else. The useEffect in this example will run after state has been instantiated and the component rendered out, and you don't need a useEffect hook to update state, you can invoke the state updater anywhere. Your question isn't very clear. Perhaps you could include a more comprehensive code example?Drew Reese

1 Answers

2
votes

The thing is when React re-renders the functional component , state hook React.useState(tabs) is not executed again.

That's why the previous state persists through the next render cycle.

So, in order for your props to derive into your inner state, you can provide the tabs props inside a React.useEffect() hook so that the useEffect callback will run again and set the state again with setList(tabs).