Make useEffect hook run before rendering the component

Viewed 3259

I've got a useEffect hook that I use in my App.js file. It puts data into redux store that I need to use in my App. But it renders before the useEffect runs, therefore the data is undefined. The useEffect then runs correctly. I need useEffect to run before anything gets rendered. How could I do that? Or what other solution should I use? I have tried removing the useEffect completely and just running the action, but that results in it running endlessly. This is my code:

function App() {
  const app = useSelector(state => state.app);
  const auth = useSelector(state => state.auth);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(authActions.checkUser());
  }, [dispatch]);

  console.log(auth.user); //undefined

  return (
    <ThemeProvider theme={!app.theme ? darkTheme : theme}>
      <CssBaseline />
      <React.Fragment>
        {/* TODO: Display drawer only when logged in */}
        {/* <Drawer></Drawer> */}
        <Switch>
          <Route exact path="/" component={Login} />
          <Route exact path="/dashboard">
            <Dashboard user={auth.user} /> //auth.user is undefined when this gets rendered
          </Route>
          <Route exact path="/register" component={Register} />
        </Switch>
      </React.Fragment>
    </ThemeProvider>
  );
}
export const checkUser = () => async dispatch => {
  let token = localStorage.getItem("auth-token");
  if (token === null) {
    localStorage.setItem("auth-token", "");
    token = "";
  }
  const tokenRes = await Axios.post("http://localhost:5000/users/tokenIsValid", null, {
    headers: { "x-auth-token": token }
  });
  if (tokenRes.data) {
    const userRes = await Axios.get("http://localhost:5000/users/", {
      headers: { "x-auth-token": token }
    });
    dispatch({
      type: CHECK_USER,
      token,
      user: userRes.data
    });
  }
};

2 Answers

I need useEffect to run before anything gets rendered. How could I do that?

You cannot make useEffect run before the initial render.

Just like componentDidMount in class components runs after the initial render, useEffect runs after the initial render and then its execution depends on whether you pass the second argument, i.e. dependency array to useEffect hook.

what other solution should I use?

You can conditionally render the content by making sure that you render the asynchronously fetched data only after it is available.

return (
   { auth ? <render content> : null}
);

or

return (
   { auth && <render content> }
);

P.S: angle brackets < or > are not included in the syntax. They are just there as a placeholder for the content that you need to render.

For details, see: React - Conditional Rendering

Alternative

You can use useMemo, which doesn't wait for re-render. It will execute same way based on dependencies like useEffect too.

useMemo(()=>{
    doSomething() //Doesn't want until render is completed 
}, [dep1, dep2])
Related