Search code examples
reactjsredux

React useEffectin App.js before children component renders


In my React App.js component I execute the following code:

function App() {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getAuthenticatedUser());
  }, []);

This code fetches the current authenticated user by session from an API and will fill the redux store. However this code seems to run after the children of App are rendered. The children components use state variables, because this function is executed after my child components are rendered it won't work. I need this function to be called once before I render my child components within App.js, how can I achieve this?


Solution

  • You can't ask React to delay rendering, that's just not how React is supposed to work (unless you're using experimental features like Suspense, but you should probably learn idiomatic React first). You normally simply tell React what to display depending on the current state/props, and React will automatically rerender as soon as something changed.

    So if you have no state variable saying that the app is in a loading state, you should make one. After all, whether it is currently loading or not is intuitively part of the current "state" of the app, especially if you are on a slow connection for instance.