Top 50 React JS Interview Questions - Updated

Top 50 React JS Interview Questions  -  Updated

If you're looking for React JS Interview Questions and Answers? If YES, then this blog is for you! There are a lot of opportunities from many reputed companies in the world. According to research, React JS has a market share of about...

If you're looking for React JS Interview Questions and Answers? If YES, then this blog is for you!

There are a lot of opportunities from many reputed companies in the world. According to research, React JS has a market share of about 7.3%.

#Interested to learn more about React framework - Then check out our Best React Course to gain expertise to build React JS Applications.

Mindmajix designed this blog with the latest 2020 updated ReactJS Interview Questions and Answers for freshers and experienced professionals. These React interview questions will help you to crack the React interview easily. Let's get into them.

Top React JS Interview Questions (Updated - 2020)
Here top ReactJS interview questions:

What is React?
Why React is used?
How React works?
What are the features of ReactJS?
What are the Advantages of React JS?
How is React different from AngularJS?
How ReactJS framework is different as compared to others?
What are the life Cycles of ReactJS?

ReactJS Interview Questions and Answers -For Beginners
**

Q1: What is React?**

Ans. React is a front-end JavaScript library that mainly follows the component-based approach for building a user interface (UI) components for a single page application. It is also used for handling the view layer in both mobile and web apps. Moreover, react plays a crucial role in developing interactive mobile and web UIs. It was created and developed by Jordan Walke; it was deployed first on the Facebook newsfeed in 2011.

Q2: Why React is used?

Ans: The following reasons make one to use React for building User Interfaces (UI), and they are:

  • Easy to learn nature
  • Simplicity
  • High scalability
  • Increase performance

Q3: How React works?

Ans. Below is the sequence of steps which gives an idea about how does react work

Firstly the react runs the diffing algorithm to identify the changes that are made in the virtual DOM.
Next step is reconciliation, this is used to update the DOM as per the new features.
Now, the virtual DOM, which is lightweight in nature and is detached from the specific implementation of the browser.
Followingly the ReactElements which are present in virtual DOM are used to build basic nodes.
Finally, if the ReactComponent changes the state; the diffing algorithm runs faster and identify the changes. After identification, it automatically updates the DOM with the change difference.

Q4: What are the features of ReactJS?

Ans: The features of React JS are as follows:

1. React improves SEO performance

React boost the performance of the SEO to higher levels as a search engine faces the problem while reading JavaScript of high loaded applications.

2. React acts as a standard for mobile app development

It provides a transition process as an ideal solution for both mobile and web applications for building rich user interfaces.

3. React makes the process of writing components easier

Using React along with JSX will make you write components and code efficiently and clearly.

4. React increases efficiency

As the React boost the efficiency of components by reusing them. This is the reason why it is considered as an ideal feature of React. It is considered as the most reusable system component.

5. React ensures stable code

It ensures the stability of the code of an application by making use of downward dataflow.

Reactjs features

Q5: What are the Advantages of React JS?

Ans: The advantages of React are as follows

Usage of JSX makes easier to read and write code
Improves the performance of applications with the use of virtual DOM
Provides an easier way to integrate with frameworks
It can be shared and rendered both on server and client-side
Writing integration and unit tests can be made smother by using tools

Q6. How is React different from AngularJS?

Ans: The following table shows the major difference between AngularJS and React

Q7: How ReactJS framework is different as compared to others?

Ans. Basically, ReactJS is a limited library that builds UI parts, it is essentially not quite the same as a considerable measure of other JavaScript structures. One common example is AngularJS approaches building an app simply by expanding HTML markup and infusing different develop such as controller at runtime. Therefore, AngularJS is exceptionally obstinate about the more noteworthy engineering of your application.

Also Read: React JS Tutorial for Beginners

Q8: Does ReactJS use HTML?

Ans. No, It uses JSX which is similar to HTML.

Q9: What is JSX?

Ans: It is basically a novel dialect of the popular JavaScript that simply integrates the HTML templates into the code of JavaScript. The browser is not capable to read the code simply and thus there is a need for this integration. Generally, WebPack or Babel tools are considered for this task. It has become a very popular approach in the present scenario among the developers.

Q10: What are the life Cycles of ReactJS?

Ans.

  1. Initialization
  2. State/Property Updates
  3. Destruction

Q11: When ReactJS released?

Ans. March 2013

Q12: How is ReactJs different from AngularJS?

Ans. The first difference between both of them is their code dependency. ReactJS depends less on the code whereas AngularJS needs a lot of coding to be done. The packaging on React is quite strong as compared to the AngularJS. Another difference is React is equipped with Virtual Dom while the Angular has a Regular DOM. ReactJS is all about the components whereas AngularJS focus mainly on the Models, View as well as on Controllers. AngularJS was developed by Google while the ReactJS is the outcome of facebook. These are some of the common differences between the two.

Q13: What is Redux?

Ans: It is one of the most in-demand libraries for front-end development in today’s growing world. It is defined as the predictable state container mainly designed for JavaScript apps and also it is used for managing the entire state of an application. Redux is very small in size and has no dependencies. It builds applications that are easy to deploy in different environments and easy to test. Redux is very small in size and has no dependencies.

Q14: What is Use of Redux thunk?

Ans: Redux thunk acts as middleware which allows an individual to write action creators that return functions instead of actions. This is also used as a delay function in order to delay dispatch of an action if a certain condition is met. The two store methods getState() and dispatch() are provided as parameters to the inner function.

Subscribe to our youtube channel to get new updates..!

In order to activate Redux thunk, we must first use applyMiddleware() method as shown below:

import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
 
//Note: this API requires [email protected]>=3.1.0
 
const store= createStore(
     rootReducer,
     applyMiddleware(thunk)
);```

Q15: What do you know about Flux?
Ans. Basically, Flux is a basic illustration that is helpful in maintaining the unidirectional data stream.  It is meant to control construed data unique fragments to make them interface with that data without creating issues. Flux configuration is insipid; it's not specific to React applications, nor is it required to collect a React application.  Flux is basically a straightforward idea, however in you have to exhibit a profound comprehension of its usage.

Q16: What is the current stable version of ReactJS?
Ans. ******Version: 16.12.0 

 

******Release on: Nov 14, 2019


### Q17: What is the Repository URL of ReactJS?
**Ans.** https://github.com/facebook/react


### Q18: What do you know about the component lifecycle in ReactJS?
**Ans.** Component lifecycle is an essential part of this platform. Basically, they have lifecycle events that fall in the three prime categories which are property updates, Initialization and third are Destruction. They are generally considered as a method of simply managing the state and properties of every reach component.

Q19: Do you think ReactJS has any limitations? If so, tell a few?
Ans. Yes, there are a few drawbacks which are associated with this platform. The leading drawback of the ReactJS is the size of its library. It is very complex and creates a lot of confusion among the developers. Also, there are lots of developers all over the world which really don’t like the JSX and inline templating. In addition to this, there is another major limitation of ReactJS and i.e. only cover one layer of the app and i.e.View. Thus to manage the development, developers have to depend on several other technologies which consume time.

Q20: How the parent and child components exchange information?
Ans. This task is generally performed with the help of functions. Actually, there are several functions which are provided to both parent and child components. They simply make use of them through props. Their communication should be accurate and reliable. The need of same can be there anytime and therefore functions are considered for this task. They always make sure that information can be exchanged easily and in an efficient manner among the parent and child components.

Q21: What is a State in React and How is it used?
Ans. In React, State is an object that represents how the component renders and behaves. States are the sources of data and allow you to create dynamic and interactive components. They are accessed using this.state(). For changing a value in the state object, call it using this.setState() method.

Q22: What are the differences between the Class component and Functional component?
Ans.

Parameter	Class Component	Functional Component
Syntax	This component requests you to extend from React. Component to create render function that in turn returns a react element	It is just a plain JavaScript function that accepts props as their arguments and returns the react element.
Life cycle hooks	Lifecycle hooks are created from the React Component. This class component makes lifecycle hooks available in it.	We cannot use lifecycle hooks in a functional component.
Readability	They are very difficult to test and read	They are much easier to test and read
Class Component Coding

1
2
3
4
5
6
7
class App extends Component {
    render () {
        return (
            <Text>Hello World!</Text>
        )
    }
}
Functional  Component Coding

1
2
3
4
5
const PageOne = () => {
    return (
        <h1>Page One</h1>
    );
}
 

Q23. What is props in React?
Ans. Props stand for properties in React and used for passing the information from one component to another. But the data with the Props are passed in a unidirectional flow, i.e., one way from parent to child. Further, they are read-only data, which means child components cannot change data coming from the parent.

React dom methods

Q24. What are the significant differences between state and props?
Ans. The difference between state and props are as follows:

State	Props
The state is completely managed within a component for internal communication.	Props are directly passed to its parents with child component.
State can be modified using setState() method.	A particular component should never modify its own props.
State changes can be asynchronous	Props are read-only
Q25. What is the higher-order component?
Ans. In ReactJS high order component can be defined as the function that is mainly used to collect the component and returns a new component. These components are the patterns that are extracted from the React’s compositional nature. One important aspect of this component is that it is used as a reusable component logic in the React. It provides us with the best way to share behaviour between different React components.

Q26: How to embed two components in One component?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React from 'react';
class App extends React.Component{
    render(){
        return(
            <div>
            <Header/>
            <Content/>
            </div>
        );
    }
}
class Header extends React.Component{
    render(){
        return(
            <div>
            <h1> Header</h1>
            </div>
 
        )
    }
}
class Content extends React.Component{
    render(){
        return(
            <h2>Content</h2>
            <p>The Content Text!!!</p>
            </div>
        )
    }
}
export default App;
Q27. What are Synthetic events in React?
Ans. React implements Synthetic events to improve the consistency and performance of applications and interfaces. The synthetic event is a cross-browser wrapper around the browser’s native event. It combines the behaviour of multiple browsers into a single API to make sure events have the same properties across different browsers and platforms.

ReactJS Interview Questions for Experienced
Q28: Give one basic difference between pros and state?
Pros are immutable while the state is mutable. Both of them can update themselves easily.

Q29: How do you tell React to build in Production mode and what will that do?
Ordinarily, you'd utilize Webpack's DefinePlugin strategy to set NODE_ENV to production. This will strip out things like prototype approval and additional notices. Over that, it's likewise a smart thought to minify your code in light of the fact that React utilizes Uglify's dead-code end to strip out advancement just code and remarks, which will radically diminish the measure of your package. 

Q30: What do you understand with the term polling?
The server needs to be monitored to for updates with respect to time. The primary aim in most of the cases is to check whether novel comments are there or not. This process is basically considered as pooling. It checks for updates approximately every 5 seconds. It is possible to change this time period easily. Pooling help keeping an eye on the users and always make sure that no negative information is present on the servers. Actually, it can create issues related to several things and thus pooling is considered.

Q31: When would you use a Class Component over a Functional Component?
If your component has state or a lifecycle method(s), use a Class component. or else, use a Functional component.

PHP Interview Questions with Solutions: Prepare for PHP Interview

PHP Interview Questions with Solutions: Prepare for PHP Interview

Prepare for PHP Interviews. Set Variable With php.ini File. Logic & Output Behind PHP Code Segment. Class Concept, Error & Functions in PHP. Start PHP Now!

Description
In this course you will be introduced with some tricky questions that everyone face during their interview. In each solutions I have included some useful functions which we generally use at the time of development also. I have covered the following area in my course with Questions, Attractive Presentations and Practical Solutions that will help you to understand the logic behind PHP in a different way.

Some useful functions
PHP error types
Class concept
Access specifiers public, private and protected
Set variable with php.ini file
Operators introduced in PHP7
Logic and its output behind some code segment
Basic knowledge
PHP7, XAMPP Server, Notepad++
What will you learn
This course is build for the person who is facing interviews. Every question is well explained with the practical solution through videos. So that everybody can prepare themselves for the tricky questions asked during interviews
To continue:

Best 50 React Interview Questions for Frontend Developers in 2019

Best 50 React Interview Questions for Frontend Developers in 2019

In this article, you'll see best React interview questions which an aspiring front end developer must prepare in 2019 for React interviews.

In this article, you'll see best React interview questions which an aspiring front end developer must prepare in 2019 for React interviews.

So, here are the Top 50 React Interview Questions and Answers which are most likely to be asked by the interviewer. For your ease of access, I have categorized the React interview questions namely:
General React Interview QuestionsReact Component Interview QuestionsReact Redux Interview QuestionsReact Router Interview Questions#

General React – React Interview Questions 1. Differentiate between Real DOM and Virtual DOM.

2. What is React?

React is a front-end JavaScript library developed by Facebook in 2011.It follows the component based approach which helps in building reusable UI components.It is used for developing complex and interactive web and mobile UI.Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.## **3. What are the features of React? **

Major features of React are listed below:
It uses the virtual DOM instead of the real DOM.It uses server-side rendering.It follows uni-directional data flow or data binding.## 4. List some of the major advantages of React.

Some of the major advantages of React are:
It increases the application’s performanceIt can be conveniently used on the client as well as server sideBecause of JSX, code’s readability increasesReact is easy to integrate with other frameworks like Meteor, Angular, etcUsing React, writing UI test cases become extremely easy## 5. What are the limitations of React?

Limitations of React are listed below:
React is just a library, not a full-blown frameworkIts library is very large and takes time to understandIt can be little difficult for the novice programmers to understandCoding gets complex as it uses inline templating and JSX## 6. What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

render(){
    return(       
          
 
 

             
 
 
# Hello World from Edureka!!

 
 
 
         
 
 
 
    );
}

7. What do you understand by Virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

This Virtual DOM works in three simple steps.
Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.

Then the difference between the previous DOM representation and the new one is calculated.

Once the calculations are done, the real DOM will be updated with only the things that have actually changed. ## 8. Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

9. How different is React’s ES6 syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in following aspects:
require vs import

// ES5
var React = require('react');
 
// ES6
import React from 'react';

  • export vs exports
// ES5
module.exports = Component;
 
// ES6
export default Component;

  • component and function
// ES5
var MyComponent = React.createClass({
    render: function() {
        return
 
 
### Hello Edureka!

 
 
 
;
    }
});
 
// ES6
class MyComponent extends React.Component {
    render() {
        return
 
 
### Hello Edureka!

 
 
 
;
    }
}

  • props
// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return
 
 
### Hello, {this.props.name}!

 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    render() {
        return
 
 
### Hello, {this.props.name}!

 
 
 
;
    }
}

  • state
// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return
 
 
### Hello, {this.state.name}!

 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return
 
 
### Hello, {this.state.name}!

 
 
 
;
    }
}

10. How is React different from Angular? **React **Components – React Interview Questions 11. What do you understand from “In React, everything is a component.”

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

12. Explain the purpose of render() in React.

Each React component must have a **render() **mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as , , etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

13. How can you embed two or more components into one?

We can embed components into one in the following way:

class MyComponent extends React.Component{
    render(){
        return(         
             
 
 

               
                 
 
 
# Hello

 
 
 
                
            
 
 
 
        );
    }
}
class Header extends React.Component{
    render(){
        return
 
 
# Header Component

 
 
 
    
   };
}
ReactDOM.render(
    , document.getElementById('content')
);

14. What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

15. What is a state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

16. Differentiate between states and props.

17. How can you update the state of a component?

State of a component can be updated using this.setState().

class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (             
                    
 
 

                   
                      
 
 
# Hello {this.state.name}

 
 
 
                 
                      
 
 
## Your Id is {this.state.id}

 
 
 
                   
 
 
 
            );
        }
    }
ReactDOM.render(
    , document.getElementById('content')
);

18. What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

//General way
render() {   
    return(
        
    );
}
//With Arrow Function
render() { 
    return(
         this.handleOnChange(e) } />
    );
}

19. Differentiate between stateful and stateless components.

20. What are the different phases of React component’s lifecycle?

There are three different phases of React component’s lifecycle:
Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.*Updating Phase: *Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.*Unmounting Phase: *This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.## 21. Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:
componentWillMount() **Executed just before rendering takes place both on the client as well as server-side.componentDidMount() **Executed on the client side only after the first render.***componentWillReceiveProps() ***– Invoked as soon as the props are received from the parent class and before another render is called.shouldComponentUpdate() **Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.*componentWillUpdate() *– Called just before rendering takes place in the DOM.componentDidUpdate() **Called immediately after rendering takes place.*componentWillUnmount() *– Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.## 22. What is an event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences like:
Events are named using camel case instead of just using the lowercase.Events are passed as functions instead of strings.
The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

23. How do you create an event in React?
class Display extends React.Component({   
    show(evt) {
        // code  
    },  
    render() {     
        // Render the div with an onClick prop (value is a function)       
        return (           
           
 
 
Click Me!

 
 
 
        );   
    }
});

24. What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

25. What do you understand by refs in React?

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

class ReferenceDemo extends React.Component{
     display() {
         const name = this.inputDemo.value;
         document.getElementById('disp').innerHTML = name;
     }
render() {
    return(       
          
 
 

            Name:  this.inputDemo = input} />
            Click           
             
 
 
## Hello  !!!

 
 
 
        
 
 
 
    );
   }
 }

26. List some of the cases when you should use Refs.

Following are the cases when refs should be used:
When you need to manage focus, select text or media playbackTo trigger imperative animationsIntegrate with third-party DOM libraries## 27. How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return(          
              
 
 

              
                 
 
 
# This is a child component

 
 
 
            
 
 
 
        );
    }
}
 
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {   
    render() {       
        return(          
             
 
 
              
                         
            
 
 
 
        
        ); 
    }
}

28. How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}
 
render() {
    return (       
         
 
 

            
                Name:
                
            
            
        
 
 
 
    );
}

29. What do you know about controlled and uncontrolled components?

30. What are Higher Order Components(HOC)?

Higher Order Component is an advanced way of reusing the component logic. Basically, it’s a pattern that is derived from React’s compositional nature. HOC are custom components which wrap another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

31. What can you do with HOC?

HOC can be used for many tasks like:
Code reuse, logic and bootstrap abstractionRender High jackingState abstraction and manipulationProps manipulation## 32. What are Pure Components?

*Pure *components are the simplest and fastest components which can be written. They can replace any component which only has a **render(). **These components enhance the simplicity of the code and performance of the application.

33. What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

React Redux – React Interview Questions 34. What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:
DOM manipulation was very expensiveApplications were slow and inefficientThere was huge memory wastageBecause of circular dependencies, a complicated model was created around models and views
35. Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

36. What is Redux?

Redux is one of the hottest libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

37. What are the three principles that Redux follows?

***Single source of truth: ***The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.***State is read-only: ***The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.## 38. What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

39. List down the components of Redux.

Redux is composed of the following components:
Action – It’s an object that describes what happened.**Reducer **– It is a place to determine how the state will change.Store – State/ Object tree of the entire application is saved in the Store.View – Simply displays the data provided by the Store.## 40. Show how the data flows through Redux?

41. How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:

function addTodo(text) {
       return {
                type: ADD_TODO,   
                 text   
    }
}

42. Explain the role of Reducer.

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

43. What is the significance of Store in Redux?

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

44. How is Redux different from Flux?

45. What are the advantages of Redux?

Advantages of Redux are listed below:
**Predictability of outcome – **Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.**Maintainability – **The code becomes easier to maintain with a predictable outcome and strict structure.Server-side rendering – You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.**Developer tools – **From actions to state changes, developers can track everything going on in the application in real time.**Community and ecosystem – **Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.**Ease of testing – **Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.**Organization – **Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.# React Router – React Interview Questions

46. What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

47. Why is switch keyword used in React Router v4?

Although a **** is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The ** **tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.

48. Why do we need a Router in React?

A Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any ‘route’ defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes with each leading to us a unique view.


    
    
    


49. List down the advantages of React Router.

Few advantages are:
Just like how React is based on components, in React Router v4, the API is ‘All About Components’. A Router can be visualized as a single root component (**
**) in which we enclose the specific child routes (****).No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the **
** component.The packages are split: Three packages one each for Web, Native and Core. This supports the compact size of our application. It is easy to switch over based on a similar coding style.## 50. How is React Router different from conventional routing?

I hope this set of React Interview Questions and Answers will help you in preparing for your interviews. All the best!

PHP Interview Questions - Top 50 Questions for PHP Developers

PHP Interview Questions - Top 50 Questions for PHP Developers

In this article, you'll see top 50 PHP interview questions from basic to advanced that you must know in 2019

PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely used open-source programming language especially suited for creating dynamic websites and mobile API’s. So, if you are planning to start your career in PHP and you wish to know the skills related to it, now is the right time to dive in. These **PHP Interview Questions and Answers **are collected after consulting with **PHP Certification Training **experts.

The PHP Interview Questions are divided into 2 sections:
Basic Level PHP Interview QuestionsAdvanced Level PHP Interview Questions
Let’s begin with the first section of PHP interview questions.

Basic Level PHP Interview Questions

Q1. What are the common uses of PHP?

Q2. What is PEAR in PHP?

PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries. It also provides a command line interface to install “packages” automatically.

Q3. What is the difference between static and dynamic websites?

Q4. How to execute a PHP script from the command line?

To execute a PHP script, use the PHP Command Line Interface (CLI) and specify the file name of the script in the following way:

php script.php

Q5. Is PHP a case sensitive language?

PHP is partially case sensitive. The variable names are case-sensitive but function names are not. If you define the function name in lowercase and call them in uppercase, it will still work. User-defined functions are not case sensitive but the rest of the language is case-sensitive.

Q6. What is the meaning of ‘escaping to PHP’?

The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as ‘escaping to PHP’. Escaping a string means to reduce ambiguity in quotes used in that string.

Q7. What are the characteristics of PHP variables?

Some of the important characteristics of PHP variables include:
All variables in PHP are denoted with a leading dollar sign ($).The value of a variable is the value of its most recent assignment.Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.Variables can, but do not need, to be declared before assignment.Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.Variables used before they are assigned have default values.### Q8. What are the different types of PHP variables?

There are 8 data types in PHP which are used to construct the variables:
Integers − are whole numbers, without a decimal point, like 4195.Doubles − are floating-point numbers, like 3.14159 or 49.1.Booleans − have only two possible values either true or false.NULL − is a special type that only has one value: NULL.Strings − are sequences of characters, like ‘PHP supports string operations.’Arrays − are named and indexed collections of other values.Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.Resources − are special variables that hold references to resources external to PHP.### Q9. What are the rules for naming a PHP variable?

The following rules are needed to be followed while naming a PHP variable:
Variable names must begin with a letter or underscore character.A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc.### Q10. What are the rules to determine the “truth” of any value which is not already of the Boolean type?

The rules to determine the “truth” of any value which is not already of the Boolean type are:
If the value is a number, it is false if exactly equal to zero and true otherwise.If the value is a string, it is false if the string is empty (has zero characters) or is the string “0”, and is true otherwise.Values of type NULL are always false.If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).Don’t use double as Booleans.### Q11. What is NULL?

NULL is a special data type which can have only one value. A variable of data type NULL is a variable that has no value assigned to it. It can be assigned as follows:

$var = NULL;

The special constant NULL is capitalized by convention but actually it is case insensitive. So,you can also write it as :

$var = null;

A variable that has been assigned the NULL value, consists of the following properties:
It evaluates to FALSE in a Boolean context.It returns FALSE when tested with IsSet() function.### Q12. How do you define a constant in PHP?

To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name.If you have defined a constant, it can never be changed or undefined. There is no need to have a constant with a $. A valid constant name starts with a letter or underscore.

Q13. What is the purpose of constant() function?

The constant() function will return the value of the constant. This is useful when you want to retrieve value of a constant, but you do not know its name, i.e., it is stored in a variable or returned by a function. For example –

<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>

Q14. What are the differences between PHP constants and variables?

Q15. Name some of the constants in PHP and their purpose.

  1. LINE – It represents the current line number of the file.
  2. ** FILE** – It represents the full path and filename of the file. If used inside an include,the name of the included file is returned.
  3. FUNCTION – It represents the function name.
  4. CLASS – It returns the class name as it was declared.
  5. METHOD – It represents the class method name.

Q16. What is the purpose of break and continue statement?

Break – It terminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.

Continue – It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Q17. What are the two most common ways to start and finish a PHP block of code?

The two most common ways to start and** finish** a PHP block of code are:

<?php [ --- PHP code---- ] ?>

<? [--- PHP code ---] ?>

Q18. What is the difference between PHP4 and PHP5?

Q19. What is the meaning of a final class and a final method?

The **final **keyword in a method declaration indicates that the method cannot be overridden by subclasses. A class that is declared final cannot be subclassed. This is particularly useful when we are creating an immutable class like the String class.Properties cannot be declared final, only classes and methods may be declared as final.

Q20. How can you compare objects in PHP?

We use the operator ‘==’ to test if two objects are** instanced** from the same class and have same attributes and equal values. We can also test if two objects are referring to the same instance of the same class by the use of the identity operator ‘===’.

Q21. How can PHP and Javascript interact?

PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a client-side language. However, we can exchange variables since PHP can generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

Q22. How can PHP and HTML interact?

It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information from HTML to PHP. PHP is a server side language and HTML is a client side language so PHP executes on server side and gets its results as strings, arrays, objects and then we use them to display its values in HTML.

Q23. Name some of the popular frameworks in PHP.

Some of the popular frameworks in PHP are:

  • CakePHP
  • CodeIgniter
  • Yii 2
  • Symfony
  • Zend Framework

Q24. What are the data types in PHP?

PHP support 9 primitive data types:

Q25. What are constructor and destructor in PHP?

PHP constructor and destructor are special type functions which are automatically called when a PHP class object is created and destroyed. The constructor is the most useful of the two because it allows you to send parameters along when creating a new object, which can then be used to initialize variables on the object.

Here is an example of constructor and destructor in PHP:

<?php
class Foo {
 
private $name;
private $link;
 
public function __construct($name) {
$this->;name = $name;
}
 
public function setLink(Foo $link){
$this->;link = $link;
}
 
public function __destruct() {
echo 'Destroying: ', $this->name, PHP_EOL;
}
}
?>

Q26. What are include() and require() functions?

The Include() function is used to put data of one PHP file into another PHP file. If errors occur then the include() function produces a warning but does not stop the execution of the script and it will continue to execute.

The Require() function is also used to put data of one PHP file to another PHP file. If there are any errors then the require() function produces a warning and a fatal error and stops the execution of the script.

Q27. What is the main difference between require() and require_once()?

The require() includes and evaluates a specific file, while require_once() does that only if it has not been included before. The require_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. So, require_once() is recommended to use when you want to include a file where you have a lot of functions.

Q28. What are different types of errors available in Php ?

The different types of error in PHP are:
E_ERROR– A fatal error that causes script termination.E_WARNING– Run-time warning that does not cause script termination.E_PARSE– Compile time parse error.E_NOTICE– Run time notice caused due to error in code.E_CORE_ERROR– Fatal errors that occur during PHP initial startup.E_CORE_WARNING– Warnings that occur during PHP initial startup.E_COMPILE_ERROR– Fatal compile-time errors indication problem with script.E_USER_ERROR– User-generated error message.E_USER_WARNING– User-generated warning message.E_USER_NOTICE- User-generated notice message.E_STRICT– Run-time notices.E_RECOVERABLE_ERROR– Catchable fatal error indicating a dangerous errorE_ALL– Catches all errors and warnings.### Q29. Explain the syntax for ‘foreach’ loop with example.

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax-

foreach (array as value)
 {
 code to be executed;
 }

Example

<?php
$colors = array("blue", "white", "black");
 
foreach ($colors as $value) {
echo "$value <br>";
}
?>

Q30. What are the different types of Array in PHP?

There are 3 types of Arrays in PHP:
Indexed Array – An array with a numeric index is known as the indexed array. Values are stored and accessed in linear fashion.Associative Array – An array with strings as index is known as the associative array. This stores element values in association with key values rather than in a strict linear index order.Multidimensional Array – An array containing one or more arrays is known as multidimensional array. The values are accessed using multiple indices.### Q31. What is the difference between single quoted string and double quoted string?

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences. For example

<?php
$variable = "name";
$statement = 'My $variable will not print!n';
print($statement);
print "<br/>;"
$statement = "My $variable will print!n"
print($statement);
?>

It will give the following output

My $variable will not print!

My name will print

Q32. How to concatenate two strings in PHP?

To concatenate two string variables together, we use the dot (.) operator.

<?php
$string1="Hello edureka";
$string2="123";
echo $string1 . " " . $string2;
?>

This will produce following result

Hello edureka 123

Q33. How is it possible to set an infinite execution time for PHP script?

The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error ‘maximum execution time exceeded.’ It is also possible to specify this in the php.ini file.

Q34. What is the difference between “echo” and “print” in PHP?

PHP echo output one or more string. It is a language construct not a function. So use of parentheses is not required. But if you want to pass more than one parameter to echo, use of parentheses is required. Whereas, PHP print output a string. It is a language construct not a function. So use of parentheses is not required with the argument list. Unlike echo, it always returns 1.Echo can output one or more string but print can only output one string and always returns 1.Echo is faster than print because it does not return any value.### Q35. Name some of the functions in PHP.

Some of the functions in PHP include:
ereg() – The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.ereg() – The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.split() – The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.preg_match() – The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.preg_split() – The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
These were some of the most commonly asked basic level PHP interview questions. Let’s move on to the next section of advanced level PHP interview questions.

Advanced level PHP Interview Questions

Q36. What is the main difference between asp net and PHP?

PHP is a programming language whereas ASP.NET is a programming** framework**. Websites developed by ASP.NET may use C#, but also other languages such as J#. ASP.NET is compiled whereas PHP is interpreted. ASP.NET is designed for windows machines, whereas PHP is platform free and typically runs on Linux servers.

Q37. What is the use of session and cookies in PHP?

A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values. Sessions have the capacity to store relatively large data compared to cookies. The session values are automatically deleted when the browser is closed.

Following example shows how to** create a cookie** in PHP

<?php
$cookie_value = "edureka";
setcookie("edureka", $cookie_value, time()+3600, "/your_usename/", "edureka.co", 1, 1);
if (isset($_COOKIE['cookie']))
echo $_COOKIE["edureka"];
?>

Following example shows how to start a session in PHP

<?php
session_start();
 
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
 
$msg = "You have visited this page". $_SESSION['counter'];
$msg .= "in this session.";
?>

Q38. What is overloading and overriding in PHP?

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method. In PHP, you can only overload methods using the magic method __call.

Q40. What is the difference between $message and $$message in PHP?

They are both variables. But $message is a variable with a fixed name. $$message is a variable whose name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.

Q41. How can we create a database using PHP and MySQL?

The basic steps to create MySQL database using PHP are:
Establish a connection to MySQL server from your PHP script.If the connection is successful, write a SQL query to create a database and store it in a string variable.Execute the query.### Q42. What is GET and POST method in PHP?

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. For example

http://www.test.com/index.htm?name1=value1&name2=value2

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

Q43. What is the difference between GET and POST method?

Q44. What is the use of callback in PHP?

PHP callback are functions that may be called dynamically by PHP. They are used by native functions such as array_map, usort, preg_replace_callback, etc. A callback function is a function that you create yourself, then pass to another function as an argument. Once it has access to your callback function, the receiving function can then call it whenever it needs to.

Here is a basic example of callback function

<?php
 
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!<br />";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!<br />";
}
 
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>

Q45. What is a lambda function in PHP?

A lambda function is an anonymous PHP function that can be stored in a variable and passed as an argument to other functions or methods. A closure is a lambda function that is aware of its surrounding context. For example

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, function ($v) { return $v > 2; });

unction ($v) { return $v > 2; } is the lambda function definition. We can store it in a variable so that it can be reusable.

Q46. What are PHP Magic Methods/Functions?

In PHP all functions starting with __ names are magical functions/methods. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. PHP provides a number of ‘magicmethods that allow you to do some pretty neat tricks in object oriented programming.

Here are list of** Magic Functions** available in PHP

Q47. How can you encrypt password using PHP?

The crypt () function is used to create one way encryption. It takes one input string and one optional parameter. The function is defined as: crypt (inputstring, salt), where inputstring consists of the string that has to be encrypted and salt is an optional parameter. PHP uses DES for encryption. The format is as follows:

<?php
$password = crypt('edureka');
print $password. "is the encrypted version of edureka";
?>

Q48. How to connect to a URL in PHP?

PHP provides a library called cURL that may already be included in the installation of PHP by default. cURL stands for client URL, and it allows you to connect to a URL and retrieve information from that page such as the HTML content of the page, the HTTP headers and their associated data.

Q49. What is Type hinting in PHP?

Type hinting is used to specify the expected data type of an argument in a function declaration. When you call the function, PHP will check whether or not the arguments are of the specified type. If not, the run-time will raise an error and execution will be halted.

Here is an example of type hinting

<?php
function sendEmail (Email $email)
{
$email->send();
}
?>

The example shows how to send Email function argument $email Type hinted of Email Class. It means to call this function you must have to pass an email object otherwise an error is generated.

Q50. What is the difference between runtime exception and compile time exception?

An exception that occurs at compile time is called a checked exception. This exception cannot be ignored and must be handled carefully. For example, if you use FileReader class to read data from the file and the file specified in class constructor does not exist, then a FileNotFoundException occurs and you will have to manage that exception. For the purpose, you will have to write the code in a try-catch block and handle the exception. On the other hand, an exception that occurs at runtime is called unchecked-exception.

With this, we have come to the end of PHP interview questions blog. I Hope these PHP Interview Questions will help you in your interviews. In case you have attended any PHP interview in the recent past, do paste those interview questions in the comments section and we’ll answer them. You can also comment below if you have any questions in your mind, which you might face in your PHP interview.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

PHP for Beginners - Become a PHP Master - CMS Project

Learn Object Oriented PHP By Building a Complete Website

PHP OOP: Object Oriented Programming for beginners + Project

Laravel PHP Framework Tutorial - Full Course for Beginners (2019)

Laravel 5.8 Tutorial from Scratch for Beginners

50+ Java Interview Questions for Programmers

Top 100 Python Interview Questions and Answers

Top 100 Python Interview Questions and Answers

Best 50 React Interview Questions and Answers in 2019

Top 50+ SQL Interview Questions and Answers in 2019

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

100+ Java Interview Questions and Answers In 2019

Best 50 React Interview Questions for Frontend Developers in 2019

Best 50 Angular Interview Questions for Frontend Developers in 2019