DEV Community

Cover image for React Virtual DOM and diffing- algorithm Simplified, Context API
Sarmin Akter Dipty
Sarmin Akter Dipty

Posted on

React Virtual DOM and diffing- algorithm Simplified, Context API

React Virtual DOM and diffing- algorithm Simplified
Virtual DOM

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. ... Since “virtual DOM” is more of a pattern than a specific technology, people sometimes say it to mean different things.

React uses the "Diff" algorithm to do this comparison. With that, React can understand which places have changed. React then changes only the part of the dom where the change was made.

Context API

You might think to yourself: "Well, I'm convinced. How do I implement Context API in my app?" First, make sure you need it. Sometimes people use shared state across nested components instead of just passing it as props. And if you do need it you should follow these very few steps:
Create a folder under your app root named contexts (not required. just a convention)
Create a file named Context.js, e.g. userContext.js
import and create a context like so:
import React, { createContext } from "react";
const UserContext = createContext();
Create a component that will wrap the provider named Provider e.g. UserProvider
Example using React Hooks:
const UserProvider = ({ children }) => {
const [name, setName] = useState("John Doe");
const [age, setAge] = useState(1);
const happyBirthday = () => setAge(age + 1);
return (


Create a higher order component to consume the context named: with e.g. withUser
Example using React Hooks:
const withUser = (Child) => (props) => (

{(context) => }
{/* Another option is: {context => }*/}

The difference between the two options above is if you want the context to be a single nested property by this name, to explode it to its properties (which in my opinion is more convenient).
Finally export them
export { UserProvider, withUser };

Image description

Discussion (0)