Interview Preparation — React & Redux-3

Welcome to part-9 of the series and third part in React & Redux questions. You can find part-8 here.

Question 53- How to pass data between sibling components using React router?
Answer- We can pass data between React sibling components using React Router using history.push and match.params.

Let look into the code. We have a Parent component App.js. We have two Child Components HomePage and AboutPage. Everything is inside a Router from React-router Route. We also have a route for /about/{params}. This is where we will pass the data.

The HomePage is a simple functional component, which have a button. On clicking the button we are using props.history.push(‘/about/’ + data) , which is used to programatically navigate to /about/data

The AboutPage is also a simple functional component, which gets the passed data by props.match.params.aboutId

The Page after clicking on button in HomePage looks like below.

Image for post
Image for post
Data “Nabendu” is passed

The GitHub repo for the same can be found here.

Question 54- What is the difference between this.state.name=”Nabendu” and this.setState({name: “Nabendu”}) ?
Answer- First of all setting the state directly by this.state.name=”Nabendu” is not recommended in React. In React we should never mutate state directly instead use setState to change the state.

One more drawback of setting state directly is that React’s lifecycle methods — shouldComponentUpdate(), componentWillUpdate(), componentDidUpdate() and render()- depend on state transitions being called with setState().

Question 55- Explain the new feature of React Memo in React v16.6?
Answer- The new feature of React Memo are used to solve the problem which we get if the state is not updating in this.setState, but still all components are re-rendered.
To solve this problem we use two solutions. One is to check and compare state in shouldComponentUpdate and if they are same, we don’t re-render components. The other solution is to use PureComponents. See question 51 for details. But both of them can’t be used with functional components.

Let’s look at the problem again. Here we have a FunctionalComp, which get same state passed every 3 sec.

The FunctionalComp is below.

So, if we run it we get value of 1 every 3 second printed like below.

Image for post
Image for post
val=1 every 3 seconds

We can solve it by wrapping the component in React.memo.

Now the output is just one 1 and after that as every time the state of it is set to one, so no more renders.

Image for post
Image for post
Only one render

You can find the Github repo here.

Question 56- Explain the new feature of Lazy loading and code splitting in React v16.6?
Answer- Lazy loading is the new feature introduced in React v16.6, which allows for some Components to load later then other components. This way we can load the components which are fast like text earlier and components which loads images a bit later.

Consider the below code for App.js. In it there are two Components ContentComponent and myComp . One have some paragraph containing lorem ipsum and other have an image to load from unsplash.
Now, we are lazy loading myComp as it have an image to load. Note the special way to import it and also we need to wrap the component in Suspense. Now, Suspense will contain the fallback Component which will be shown while myComp gets loaded.
The other component ContentComponent will load instantly.

React is very fast and in localhost condition to see it, we have to emulate Slow speed. To do so open the console, and goto Network tab. Then click on Online and select Slow 3G.

Image for post
Image for post
Slow down the internet

Now, when you refresh the local running app, you can see Loading….. coming.

Image for post
Image for post
Loading… coming

You can find the GitHub repo here.

Question 57- Explain the flow in a React-Redux app?
Answer- As on Redux site “Redux is a predictable state container for JavaScript apps.” Redux can be used separately, but it gained much popularity because it was able to solve the state problem in a React app.
In React to pass data(or state) between component we use props to be passed from Parent to Children. If the data needs to be passed to Components 5 level deep then it have to just have to pass through 4 Components, which doesn’t require it. Passing data from Child to Parent is also a problem, and we need to use Callback function. This gets complicated soon in large application.

So, to solve this issue we maintain state, which is the main data of the application in a central location. It can be access by any Components which ask for it.

Let see the complete flow.

The Container is a file that corresponds directly to a single component. It have two functions called ‘mapDispatchToProps’ and ‘mapStateToProps’.
As in the code below, when the Component loads we have a function call to this.showPopGraphs();
It will go to ‘mapDispatchToProps’, which dispatches it to the action creator.

The Action Creator. In this file, you will write the functions that dispatch an action. It perform some action, like an API call using axios. When we get the response back from it, we will dispatch an Object with “type” and “data” as { type: GET_INDIA_DATA, indPopData: response.data }
Now this will be heard by only one type of function: the reducer.

The Reducer hears an action , and can now generate a new state based on what the action wants it to do. Note the the state never actually changes in Redux, but instead the reducer generates a new state which is a copy of the old state.
In the code below we don’t mutate the state but create a new state by Object destructuring.

Back to Container the result is received by “mapStateToProps”. It can be accessed as a props ie “this.props.indPopData” in this case. Here, we are also data massaging the data in componentWillReceiveProps and storing it in local state variables “indPieData” and “indPopTotal
After that it is rendered in the component using “this.state.indPopTotal” and “this.state.indPieData”

The GitHub repo for the above code example is here.

Question 58- What is the use of middleware Redux thunk?
Answer- Redux thunk is a middleware which sits between action creator and reducer in the React-Redux flow. It is very useful when we do asynchronous API calls with fetch or axios, which returns a Promise and we then dispatch it to reducer.

Redux thunk mainly works behind the scene. We have use some boiler-plate to use it.

In Question 57 for React-Redux flow, in action creator we call an API end point with axios. It is a network request and will take some milliseconds or more depending on the connection.
Now, thunk middleware sort of wait for that call, which is a Promise to completed. Once we get the response, which contains the data then only it dispatches it to reducer.

So, Redux thunk is required in Projects where we do API calls to some endpoint.

The GitHub repo for this is here.

Question 59- What are Pure Functions and how they are used in reducers?
Answer- A Pure function is a function which :
* Given the same input, will always return the same output.
* Produces no side effects.

Consider the below example:

Even though we didn’t pass any arguments into any of the function calls, they all produced different output, meaning that `Math.random()` is not pure.

Now consider the below add function doesn’t alter “a” or “b”, always returns the same output for the same input.
So, it’s a “pure” function

The second condition is that it should not produce any side effects. It basically means it should not change any external state.
Consider, the below code. The function addNum changes the values of external “a”, so it’s not pure function.

Reducers are Pure Functions as they don’t mutate the state. It generates a new state which is a copy of the old state.

This concludes the part-9 of the series and last part of React & Redux questions. You can find part-10 here.

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store