React for Angular developers
React for Angular developers
It is said that a fresh mind is easier to train than the one already trained in something !!
Switching to a new frameworks is not easy. I think that is true for experienced developers specifically. Since we have already developed a mental model and understanding of the earlier framework. The same thing happened to me when I decided to explore React JS a few months back. Being an Angular developer initially, I found it a little difficult to wrap my head around the new concepts. Back then I used to think in Angular and convert it to React. It's like learning a new language, where we try to think in our native language and then translate it. Eventually, we get the hang of the new language and no longer require translation.

In this article, we will use the same approach to understand React concepts. Even though concepts and implementations are not 100% the same but we will get a hint. Today we will discuss the fundamental concepts of React i.e. JSX, Props, and States. As a beginner, we will see the common mistakes and understand the rationale behind them. I hope it will help you to create a good mental model and reduces the chances to introduce bugs🐞.
Fundamentals
Note: Since the introduction of Hooks, functional components are gaining more traction than class-based components. So in the rest of this article, we will see functional components in action. Please feel free to explore the class-based equivalents. Here is a great article on the benefits of functional components.
Component structure

Unlike Angular, React doesn't have separate HTML files. Here we use JSX syntax for markups.
import React from 'react';
function HelloWorld() {
return <div>HelloWorld</div>;
}
export default HelloWorld;
Coming from an Angular background, we tend to write a lot of HTML codes in a single component. Angular provides multiple ways to segregate and reuse the HTML codes like the usage of ng-templates, content-projections, etc. But in React, we could end up with messy and unmaintainable code soon, if not handled properly.
Rewiring Tips 💡:
-
Always follow the
Single Responsibility Principle
, i.e. the component should have a single thing to take care of. -
Use Smart component - Dumb component approach -
Smart component: It is also known as the Stateful component. These components maintain a state of their own and have business logic to manage them.
Dump component: It is also known as the Stateless component. These components don't contain any business logic. It solely relies on the information coming from the parent component (i.e. Prop) to render the UI. It makes the component more reusable, and it is easy to follow single responsibility.
Suppose there is a component having a lot of UI stuff. In this case, we will try to find the smallest independent pieces. Each small piece can be converted into a Stateless component. And the parent component will maintain the state and business logic. This way we can make the component more organized and readable.
Questions to ask during the analysis:
- Is your component having multiple things to do?
- Is your component having something that can be reused in other places?
- Is your component having lots of lines but only a few of them are executed at a time conditionally?
JSX is HTML ?

This is a common misconception among beginners. But please remember, JSX is NOT Html, even though it looks similar. JSX is Javascript syntax and a syntactical sugar for React.createElement()
. React converts it into bunch of React.createElement()
statements during rendering phase. React Docs has a nice explanation for it.
Let's see some of the common mistakes we do while writing JSX.
- Incorrect letter casing of Component name
function HelloWorld() {
return (
<text value={'Hello World !'} /> // ❌
);
}
function text({ value }) {
return <div>{value}</div>;
}
Here text
will be treated as an HTML tag, rather than a React component. Let's see why?
JSX allows us to use native HTML tags as well as user-defined tags (AKA Components). During the rendering phase, react checks if:
- The tag starts with lowercase, then treat as a native HTML tag.
- The tag starts with uppercase, then treat as a component and convert to React.createElement(ComponentName).
- Using the
class
attribute As we know, to apply CSS classes we useclass
attribute. But in Javascript,class
is already a reserved keyword. Therefore in JSX we should useclassName
instead.
<div className="text-center"></div>
- Return multiple sibling tags
function Comp() {
return (
<p>Text 1</p>
<p>Text 2</p>
)
}
The above snippet will throw an error JSX expressions must have one parent element
. This means the component can only render one root element, but the root element can have multiple children elements.
But sometimes we genuinely need sibling elements, then how to fix it?
There are multiple ways to fix it.
- Fix 1
Wrap it inside another HTML tag e.g.<div>
return (
<div>
<p>Text 1</p>
<p>Text 2</p>
</div>
);
- Fix 2
In case we do not want<div>
element in the DOM, we can go forReact.Fragment
. It is equivalent to<ng-container>
in Angular.
return (
<React.Fragment>
<p>Text 1</p>
<p>Text 2</p>
</React.Fragment>
);
This will be rendered as
<p>Text 1</p>
<p>Text 2</p>
- Fix 3
Wrap the component with<></>
, which is a shorthand forReact.Fragment
and works similarly.
return (
<>
<p>Text 1</p>
<p>Text 2</p>
</>
);
- Using the index as a
key
attribute inside the loop
React needs these unique keys to keep track of the changes in elements. Sometimes we simply use the index as the key, which works just fine. But it will lead to performance issues for large-size data.
Let's check the below example:

In this example, the 5th element (index 4) is deleted and the following elements shifted 1 index to the left. React has to rerender everything, to update the UI properly. It will lead to performance issues in the case of large Lists.
function HelloWorld() {
const [list, setList] = useState([
{ id: 1 },
{ id: 2 },
{ id: 6 },
{ id: 4 },
{ id: 5 },
]);
useEffect(() => {
setTimeout(() => {
setList(list.slice(1));
}, 2000);
}, []);
return (
<>
<Text value={'Hello World !'} />
{list.map((el, index) => (
<Text key={index} value={el.id}></Text>
))}{' '}
// ❗️ not encouraged
{list.map((el, index) => (
<Text key={el.id} value={el.id}></Text>
))}{' '}
// ✅ Optimized & recommeded way
</>
);
}
function Text({ value }) {
return <div>{value}</div>;
}
Let's see how both the snippets perform:
- Index as a key

- Unique Key

In the second case, we can see how React JS smartly identifies the changes and updates only that specific part. It reduces the DOM operations and that will improve performance.
Awesome folks, we have reached the 1st milestone 🏁. Now let's look at the other important concepts i.e. Props and states.
Props and States
Prop - It is an object which stores the value of attributes of a tag. We can think of it as parameters sent to the function. Using Props data from the parent component flows to the child component. It is similar to the @Input() in Angular.
function HelloWorld() {
return <Text value={'Hello World !'} />;
}
// Here 'value' is a Prop and passed as a parameter
function Text({ value }) {
return <div>{value}</div>;
}
Props
are more like a static value that should not be modified, but why 🤔??
Official React docs have a nice explanation for this. Please visit
State - the State of a component is an object that holds some information that may change over the lifetime of the component.
function component() {
const [counter, setCounter] = useState(0);
return <div>{counter}</div>;
}
Let's see how States work internally. Below is a sample implementation for the useState
hook :
(function React() {
let state; // closure memory
function useState(initialValue) {
state = state || initialValue;
const setState = (currentValue) => {
if (typeof currentValue === 'function') {
state = currentValue(state);
} else {
state = currentValue;
}
console.log(`[State Updated] new state:${state}`);
};
return [state, setState];
}
function Component() {
const [counter, setCounter] = useState(0);
console.log(`[Component rendered] state : ${counter}`);
setCounter((counter) => counter + 1);
}
Component(); // first render
Component(); // Suppose component is rerendered
})();
let's execute and see it in inspector tool:

In the above example, we can see useState
internally uses closures which is a core javascript concept. This is how components still remember their states after multiple rerenders.

Changes in Props and States initialize the
render phase
, where React creates a newVirtual DOM
. Then new V-dom is compared with the existing V-dom. This process is called thereconciliation
. Then the difference is updated to the real DOM. This is known as thecommit phase
.
Mistakes we do as beginners [Rewiring Time ⏰]
Before we discuss the issues, here is an Angular Snippet for reference
private string counter = 0;
add() {
this.counter += 1;
console.log('value = ', this.counter); // value = 1
}
//In HTML
<div>{{counter}}</div>
// renders 1 after the update
- Updating State directly:
const [counter, setCounter] = useState(0);
const add = () => {
counter += 1; // ❌
setCounter(counter + 1); // ✅
};
**The why ??**
1. We are updating local values, that react can not observe. Hence UI will not be updated.
2. Since `useState` batches the changes and updates in an asynchronous way, there is a strong
possibility that our local value might be overridden with some old/unexpected value.
- **Using state immediately after updating the state**
```javascript
function Component() {
const [counter, setCounter] = useState(0);
const send = (val) => {
console.log(val);
}
const sendAnalytics = () => {
const oldValue = counter;
send('old value: ' + oldValue);
setCounter(counter + 1);
// expected -> old value: 0 New value: 1
// actual -> old value: 0 New value: 0
send(' New Value: ' + counter ); // ❌ incorrect place
}
return (
<button onClick={sendAnalytics}>Send</button>
)
}
The why ??
Unlike Angular, React does not update the state synchronously. Therefore we should not consume the state immediately after setting it.
How to fix it?
Here comes a new Hook useEffect
to rescue:
function Component() {
const [counter, setCounter] = useState(0);
const send = (val) => {
console.log(val);
};
const sendAnalytics = () => {
const oldValue = counter;
send('old value: ' + oldValue);
setCounter(counter + 1);
};
useEffect(() => {
// ✅
// expected -> old value: 0 New value: 1
// actual -> old value: 0 New value: 0
send(' New Value: ' + counter);
}, [counter]);
return <button onClick={sendAnalytics}>Send</button>;
}
- **Incorrectly updating State object / mutating existing object **
function MyComponent() {
const [myState, setMyState] = useState({
name: 'My Name',
age: '',
});
const updateAge = (newAge) => {
myState.age = newAge;
setMyState(myState); // ❌
setMyState({
age: newAge,
}); // Partially ❌
setMyState({
...myState,
age: newAge,
}); // ✅
};
}
Let's discuss what is happening above.
- Issue 1
myState.age = newAge;
setMyState(myState); // ❌
This is not a correct way to update the state Because React compares the previous state with the updated state to decide if the component needs to be re-rendered. Here the object reference
is not changing, hence React can not detect the change and will not re-render the UI.
ex -
const state = {};
const newState = state;
newState.val = 5;
state === newState
// true -> because it is still pointing to the same memory reference
A similar issue can be reproduced with arrays also, Where we can directly mutate the value likearr.push('val')
.
Fix:
const oldObj = { name: 'Ben', age: 10 };
const newObj = { ...oldObj, age: 15 }; // name: 'Ben', age: 15}
const oldArr = [1, 2, 3, 4];
const newArr = [...OldArr, 5]; // [1,2,3,4,5]
- Issue 2
setMyState({
age: newAge,
}); // Partially ❌
Here we are creating a new Object which is correct. But we forgot to copy other properties. In this case, we lost name: 'my name'
property. The mentioned fix will help to resolve this.
Huh! That's a lot of things we discussed today. Hopefully, this list will help you to avoid the most common React issues and improve your understanding. I would love to receive feedback from you. Please give a reaction of your choice if you like this article.
Thank you so much for your precious time. Have a nice day !!