Theres no place like home!

Redirect with React Router and Hooks

Eric Bishard
April 26th, 2019 · 2 min read

A lot of these short blog posts are just for me to find later when I forget how to do something, but I thought this little trick that you can do with React router was worth sharing.

To set the stage, I have an application with routing and pages already set up.

1<main>
2 <Switch>
3 <Route exact path="/" component={Home} />
4 <Route exact path="/todos" component={Todos} />
5 <Route exact render={() => <h2 className="four-ofour">404 Page Not Found</h2>} />
6 </Switch>
7</main>

One of the routes loads a Todo component in which I employ the useReducer hook in order to keep track of the todos state (local state). I have contrived a very simple feature that will redirect the user to the Home route once the Todos are cleared. Without thinking of all of the edge cases for this feature, I just want to get a basic redirect working using some basic logic, a quick and dirty example and we can iron the details out later if we want to.

If we look at the Todos.js file, we will see that we have a function that calls dispatch() and sends CLEAR_TODOS as an action type to our reducer.

1/* After clearing Todos,
2 wait two seconds and then set toHome to true
3 (in JSX we can render a <Redirect> component based on toHome's value) */
4function clearTodos() {
5 dispatch({ type: 'CLEAR_TODOS' })
6 setTimeout(() => setToHome(true), 2000)
7}

In my contrived example, I know that I want to at the very least redirect to Home once the user clicks on “CLEAR TODOS”, in a better example I would notify the user (which I am not doing in this code) and then redirect to Home because our todo list is cleared. So what I want to do here is tap into a Hook that I will create which has a state variable named toHome and a related set/update method called setToHome(). The code below is a standard useState hook:

1/* create a piece of state (toHome)
2 with a method to update that state (setToHome)
3 and give it a default value of false */
4const [toHome, setToHome] = useState(false)

In order to make the page redirect when the toHome state variable is set to true, we just need to render a regular Redirect component from React Router and we will use a ternary statement to inline that component if true and if not, we will use null or render nothing:

1return (
2 <>
3 /* if (toHome) is true
4 ? then we render a React Router <Redirect> component
5 : otherwise we do null/nothing gets rendered */
6 {toHome ? <Redirect to"/" /> : null}
7 </>
8)

Here is a link to the specific commit that has this redirect setup: 4ed5c6

As well a link to the overall example application, which by the way has some other cool responsive stuff going on, check it out!

If you are new to Hooks and would like to read up on the subject, I have several articles that cover topics from Basic, Advanced and Custom Hooks as well as a talk on Hooks with links provided below if you are interested!

Articles on React Hooks: How to Use Basic React Hooks for State and Effects
How to Use Basic React Hooks for Context
How to Use Basic React Hooks for Reducers
Everything You Need to Create a Custom React Hook

My Talk on React Hooks: Getting Hooked on React

More articles from Eric S Bishard

Angular to React in 30 Days

A short article about my experience as an Angular developer tasked with learning React...

December 24th, 2018 · 6 min read

All the RAGE with Couchbase Server

Let's build a full-stack JS app with React, Apollo, GraphQL and Express using Couchbase Server as a datastore.

September 23rd, 2020 · 15 min read
Made with 💧 😅 & 😂's in the East Bay
Link to $https://twitter.com/httpjunkieLink to $https://github.com/httpjunkieLink to $https://www.linkedin.com/in/eric-b/Link to $https://stackoverflow.com/users/2623804/eric-bishardLink to $https://medium.com/@httpjunkie