1

I have a <Loading /> component that wraps all routes in my app.
The <Loading /> component has a property isLoading that receives a Redux state variable, that tells if the Loading component will be visible or not.

function App() {
    const isLoading = useSelector((state) => state.loading.value)
    
    return (
        <Loading isLoading={isLoading}>
            <BrowserRouter>
                <Routes>
                    <Route path='/' element={<Hypertube />} />
                    <Route path='/login' element={<Login />} />
                    <Route path='/register' element={<Register />} />
                </Routes>
            </BrowserRouter>
        </Loading>
    );
}

When the user opens a page, I need to change the Redux state to true, so the <Loading /> component will be visible (and then hide it when the page gets rendered).
So what I need, is to change the state before the functional component gets rendered (or while the component is rendering).

I wanted to use componentWillMount(), but it's deprecated now.

A solution to this (that I don't like) is to do this 2 changes:

  1. Set the default redux state value to true, so we can see the loading whenever the page get opened for the first time.
  2. Change the state value to true whenever the user get redirected to another page.
1
  • Why isn't the default value true? Commented Nov 15, 2022 at 17:19

1 Answer 1

2

How to call a function before a functional component render in ReactJS

Theoretically you could dispatch an action on component's mount (in useEffect hook) to set the loading state to true, but a single flick may be visible (because the component will have to re-render).

A standard solution for it is to set the default value of state.loading.value to true in the redux store.

If you want to set the loading value to true with every route change, you could e.g. listen to the location change:

import { useLocation } from 'react-router-dom';

const location = useLocation();

useEffect(() => {
   dispatch(setLoadingToTrueAction());
}, [location]);

Or you could just dispatch this action in every component within useEffect where you want the loader to appear.

Sign up to request clarification or add additional context in comments.

4 Comments

@arrmani88 You want to show the loader with every route change, right?
should I add this only in App() function ?
@arrmani88 Check firstly if it works for you well :)
Sorry for this late answer, thank you so much your solution is working, I also will let you know if I find a way how to call a function before a functional component render

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.