Categories
frontend javascript reactjs

When to use the useRef hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useRef hook and understand how and when to use it.

What is the useRef hook ?

useRef hook is something that I briefly discussed in one of my articles where I described useRef hook as something equivalent to

Removing the state updating function from the useState, so basically just extracting the piece of state and take away the ability of state updation. This is something that will be equivalent to the useRef hook. I also discussed in that article that both the ref and state values persists across renders, so it is not the case that on every subsequent re-render they get set back to some default. So do make a note of the above points.

useRef is a React Hook which accepts a single argument as the initial default value and gives us something called as a ref. A ref is kind of an object that has a property called as current.

Let us see an example :

function SomeComponent() { 

    const usernameRef = React.useRef(''); 
    const handleSomething = () => { 
       console.log(usernameRef.currrent); 
       usernameRef.current = someOtherValue; 
    }
}

Now the things to note here is that usernameRef.current is used to access the value of the ref and if we want to update the ref value, then we can simply do so by setting usernameRef.current to a value of our choice.

To know more about refs, check my existing article on useRef hook. Here is the link for the same :

Image description

https://dev.to/thenerdydev/useref-hook-useref-vs-usestate-3i7k

In the above article, I have also taken some examples where I have demonstrated the usage of the useRef hook, we have discussed :

1. Ref Example – 1 (An Interval Timer)
2. Ref Example – 2 (Working with DOM using refs)
3. The third thing that we discussed in that article was :

useRef just like useState persists a value across renders but unlike useState it does not trigger a re-render of the component.

So in essence,

useRef = useState – state updating function

If you don’t know about the useState, no worries. You can learn about the same in this article :

https://dev.to/thenerdydev/react-hooks-demystifying-the-usestate-hook-in-under-10-minutes-examples-video-29ab

Let’s sum up what we learnt :

A ref is a plain JavaScript Object
{ current: <some_value> }

If you want to create a ref with the current value as null, then you can also make use of the createRef method,
React.createRef()

This gives us :
{ current: null }

Next, useRef(someInitialValue) also gives us a ref { current: someInitialValue }. The interesting thing about useRef is that it memoizes this ref so that it stays persistent across multiple renders of the component.

Another point to make a note of is that :

useRef(null) is basically equivalent to useState(React.createRef())[0]
But this kind of abuses the functionality.

Lastly, we learnt that useState causes a re-render in contrast to useRef. The state and the ref values (both) persist across re-renders.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Categories
reactjs

Memoizing with React.useMemo

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useMemo hook and understand how and when to use it.

What is the useMemo hook ?

useMemo is a React Hook that was introduced to memoize expensive computations. Let us understand some basics about this. In order to understand the useMemo hook, let us understand its syntax:

const memoResult = useMemo(someFunction, dependencies);

So what happens with useMemo is that when the component renders for the first time, the useMemo hook invokes the someFunction (it could be any function, I am just calling it as someFunction) and memoizes the value that it computes for us and then it returns the result back to the component. Now the interesting thing here is that if during the subsequent renders, the list of dependencies that we specify do NOT change, then in that case useMemo will not invoke the someFunction but instead it will return the memoized value. Contrary to this, if the list of dependencies experience a change during subsequent renders, then useMemo will invoke the someFunction, memoize the result that it gets as a result of computation and then return it back to the component. So in essence, this is what happens in the useMemo hook.

Now let us see a simple example :

Let us say we have a component that deals with computation of factorial of a number, let’s call the component as FactorialResult. Now what this component does is that it computes the factorial of a number that is supplied into the input field by the user. Let us see the basic code for same :

import React from 'react' 
function computeFactorial(num) { 
   if(num == 0) { 
       return 1;
   }
   return num * computeFactorial(num - 1)
}
const FactorialResult = () => { 
  const [num, setNum] = React.useState(0); 
  const factorial = computeFactorial(num); 

  const handleChange = event => { 
         setNum(+event.target.value); 
  }
  return ( 
    <div>
      Factorial of 
      <input type="number" 
       value={num} 
       onChange={handleChange} />
      is {factorial}
    </div>

   );
}

Now every time, you change the input value, the factorial is re-calculated as a result of re-render.
Now how can we memoize this factorial calculation which itself is an expensive operation ? We want to memoize the factorial computation when the component re-renders. So for this we can make use of the useMemo hook. Let us make small changes in our code and memoize this factorial calculation. So here is the new code for the same component :

import React from 'react' 
function computeFactorial(num) { 
   if(num == 0) { 
       return 1;
   }
   return num * computeFactorial(num - 1)
}
const FactorialResult = () => { 
  const [num, setNum] = React.useState(0); 
  const factorial = React.useMemo(() => {
      computeFactorial(num)
   },[num]); 

  const handleChange = event => { 
         setNum(+event.target.value); 
  }
  return ( 
    <div>
      Factorial of 
      <input type="number" 
       value={num} 
       onChange={handleChange} />
      is {factorial}
    </div>

   );
}

Now every time you change the value of the num, the computeFactorial will get invoked but only if the num has changed. If num does not change on the re-render, then it will return the memoized result for its factorial and will not make that extra computeFactorial call. I hope that makes perfect sense.

Let’s see one more example to make the useMemo hook extremely clear.

Let us say we want to return the full name of a person, so for this let us say we have a function in some component that gives us the full name:

const fullName = React.useMemo(() => {
   return firstName + " " + lastName
},[firstName, lastName])

In above code, if the firstName or lastName change, then our fullName function will get re-invoked because we have specified firstName and lastName as dependencies. Please note : functions themselves usually don’t need to be re-computed, and their dependencies are mostly closure values that may change.

const fullName = React.useCallback(() => {
     return firstName + " " + lastName
}, [firstName, lastName]);

Now for above piece of code when firstName or lastName change, we don’t need a separate instance of the function on each re-render of the component, but we need exact the one and same instance of the function so that it has up to date values in the closure.

So this is it for this article. Thanks for reading.

Categories
reactjs

🐱‍👤When to use the useCallback hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useCallback hook and understand how and when to use it.

What is the useCallback hook ?

useCallback is a React Hook which was introduced to prevent re-creation of a specific function in case our component re-renders.
It does so by memoizing the callback function that this hook takes and this memoized version will only change when one of the inputs has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

So typically we should make use of the useCallback hook in one of the following cases :

  1. If you are passing the function on to child component as props and the child component doesn’t often need re-rendering except when a certain prop change then useCallback might prevent certain re-renders.
  2. You are specifying a function as a dependency to useEffect. In such a case you must ensure that the function is not recreated on every render or the useEffect will be triggered on every render.

So in the essence, the decision to make use of the useCallback must be made judiciously instead of blindly since you might just overdo the advantage offered by useCallback and end up degrading the performance since useCallback will also memoize the functions and a frequently changing dependency might anyways need to recreate the function.

If the dependencies of the useCallback change, only then the function will get recreated otherwise it will use the exact one and the same instance of that function across the re-renders.

Example :

In JavaScript, we know that when a function gets executed we know that each and every thing (variables functions, objects etc) that is present within the function gets re-created into the memory. So this happens on each execution of the function. Now for a function we might not want it to get re-created on each re-render of the component and in turn we may want to use the exact same instance for that specific function in each of our renders. We might only want to re-create the function when a specific dependency which that function uses gets changed and NOT otherwise. This is something that we can achieve by making use of the useCallback hook.

Let’s see a simple Counter component.
Here we have a single piece of state which we call as counter and we have a corresponding state updating function for it which we named as setCounter. The initial value for counter is given as 0.
Next we have a handleIncrement counter function and all it does is that it increments the value of counter by 1.

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = () => {
    setCounter(counter + 1);
  }

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement}>Increment</button>
  </div>
}

Now the interesting thing to note here is that the handleIncrement function will get re-created on each render of the component. This means that each time the component re-renders, handleIncrement function will get re-created at a separate spot in memory. And due to this reason, when React tries to make a referential equality comparison, it finds a change because of the re-creation of the handleIncrement function.

Now what if we wrap this with the useCallback hook ?

What the useCallback does is that it internally caches the first created version of the function and returns it to the caller if the listed dependencies haven’t changed. In case the listed dependencies does change, then it automatically gives us a new instance of that function.
So if we introduce the useCallback hook into our above code, then our code should look something like this :

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = React.useCallback(() => {
    setCounter(counter + 1);
  }, [])

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement }>Increment</button>
  </div>
}

Now with the above code, what React will do is that it will cache the handleIncrement function internally and will make sure to return the exact same instance of the function in case no external dependencies of the useCallback have changed. In case, the external dependencies do change, then in that case a brand new instance of the handleIncrement function will get created for us. For our case, there are no external dependencies for the handleIncrement function.

Now caching the function internally by using the useCallback has its own cons. The cached instance of the function call will not have direct access to the variables of our current function call. Instead of that it will have visibility of the variables that were introduced in the initial closure call where the stored function was created. So in essence, this means that our call will not work for the updated variables. Therefore, we need to specify those variables or dependencies of the function that can change. The list of dependencies is to be passed as the second argument of the useCallback. In our example, we need to tell to useCallback function that we need a fresh version of our counter variable on each call. If we don’t do that, then the counter variable after the call will always be 1 and this is what comes from the original value 0 plus 1.

const Counter = () => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = React.useCallback(() => {
    setCounter(counter + 1);
  }, [counter])

  return <div>
    Counter:{counter}<br/>
    <button onClick={handleIncrement}>Increment</button>
  </div>
}

The above version of code will not re-render on every call.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs web development

React.js – How to use Refs in React.js

Using refs in React.js

Hey guys 👋🏻,
In this article, let us cover the topic of How to use Refs in React.js

Let us investigate why React.js, a library that keeps your code away from DOM manipulation, keeps its doors open for you to access. React rethinks a view as a result of a state of a component. It provides JSX, a syntactic sugar over JavaScript, to design the view layer and then modifies the DOM itself rather than giving the control to the developer.

Still, the React team provided escape routes and kept the library open for certain situations that go beyond the scope of what React is designed for.

Creating Refs

Refs are escape routes and it’s better to avoid them whenever possible. When we obtain a DOM element using ref and then later modify its attribute, we might enter into a conflict with React’s diff and update approach.

Let’s start with a simple component and grab a DOM element using ref, assuming that you already know how to set up a basic react app.

In the above piece of code, we are using a react hook useRef to create and initialize a variable called buttonRef. We then assign buttonRef to ref attribute on button JSX element.

Using React refs

As we discussed earlier in this article we are declaring views based on the state, and though we are still altering the state using functions, we are not in direct control of the DOM changes. But in a few use cases, it makes sense to introduce refs in your code.

Focus Control

To better understand the problem statement let’s storify the situation.

Alex is a software development intern at Metflix Inc. and his manager has given him the task of creating contact forms. The manager has asked him to focus on the first input element in the form when a modal is opened. Alex is confused about how he can achieve this in React.js. Let’s help Alex out.

The first thing we need to do is to get a reference to the input.

Next, when our modal loads, we imperatively call focus on our input ref.

Note: You need to access the element through the current property of the ref you declare.

Detect if an element is contained

Similarly, we would want to take an action in the app when an event is dispatched. Like close the modal when the user clicks outside of it.

Here, we are checking if the user click is out of the modalRef limit. If it is we are calling close() function from props to close the modal.

Integrating DOM-based libraries

Like React, there are other utilities and libraries outside its ecosystem that have been in use for years. To use such libraries, refs come in handy.

GreenSock library is a popular choice for animation examples. To use it, we need to send a DOM element to any of its methods.

Let’s go back to our modal and add some animation

Forwarding Refs

Refs are useful for specific actions. The examples shown are a little simpler than what we usually find in a real-life web application. We need to deal with complex components and we barely use plain HTML elements directly. It’s common to use a ref from one component in another component.

The issue now is that passing a ref to this component will return its instance, a React component reference, and not the input element we want to focus on like in our first example.

React provides forwardRef, which allows you to define internally what element the ref will point at.

Now, when a parent component passes a ref value, it’s going to obtain the input, which is helpful to avoid exposing the internals and properties of a component and breaking its encapsulation.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs

React.js – Demystifying Virtual DOM

Hey guys 👋🏻,
In this post, let us talk about Virtual DOM in React.js.

For this post we will understand Virtual DOM
✔ What is Virtual DOM ?
✔ Why we need Virtual DOM ?
✔ Why Virtual DOM is faster and more efficient than real DOM ?

Image description

Why Virtual DOM ?

The DOM as we know represents the UI of your application. Every time there is a change in the state of your application UI, the DOM gets updated to represent that change. But the problem is that frequently manipulating the DOM affects performance, making it DEAD slow !

When changes are made to some element, the updated element and it’s children have to be re-rendered to update the application UI. The re-rendering of the UI is what makes it slow.

✔ More the UI components you have, more expensive will be the patches to the DOM as they would need to be re-rendered for every DOM update

👉🏻 Hence the need for Virtual DOM in React.

Now coming to question, what the heck is Virtual DOM 🤔?

The Virtual DOM is only a virtual representation of the DOM. Every time the state of our application changes, the virtual DOM gets updated instead of the real DOM.

Virtual DOM is faster and more efficient ..

Image description

When new elements are added to the UI, a virtual DOM is created which is a tree like representation. Each element is a node on this tree. If the state of any of any of these elements changes, a new virtual DOM tree is created. This tree is then compared or “diffed” with the previous virtual DOM tree.

Once this is done, the virtual DOM calculates the best possible method to make these changes to the real DOM. This ensures that there are minimal operations on the real DOM. Hence, reducing the performance cost of updating the real DOM. This updated tree is then batch updated to the real DOM.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs

React.js – What is Props ?

Hey guys 👋🏻,
In this post, let us cover what actually are props in React.js

For this post we will first understand Props
✔ What is Props ?
✔ Understanding Props
✔ Accessing Props in Functional and Class based Components
✔ Examples of Props

Image description

Introduction to Props

Props are used to make components configurabledynamic and flexible. Every HTML element as we know has some attributes like input element has valueplaceholder etc. It is dynamic content that you can configure from outside.

Understanding Props

Our components which are customized HTML elements can also be passed some arguments in form of attributes known as props so as to configure just like any other HTML element is configured and it is the parent component that passes these arguments to the child component.

Every child component receives props as an argument that is passed to it by React which is an object that holds the arguments that the parent component passed to the child component and that object is known as propsprops basically means all the properties that a component is receiving from outside.

When using functional components, you can access the props using the below syntax :

props.<propName>

When using class components, you can access the props using the syntax :

this.props.<propName>

EXAMPLES

Passing a prop of brand to the Computer component :

Image description

Defining our Computer component which receives the brand prop.

Image description

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs

React.js – What is State ?

Hey guys 👋🏻,
In this post, let us cover an introduction to State in React.js.

For this post we will understand
✔What is State in React ?
✔ Example for creating State in React.
✔ Accessing the State
✔ Using setState and understanding its pitfall.
✔ Using setState with callback to resolve the pitfall.

Image description

Introduction to State

Every component manages its own state. With the introduction of React Hooks, you can also use state in functional components. But in this article, we will discuss about state in class components.

Example for creating state :

We define a state property inside the constructor function.

Image description

To access the state

To access the counter property defined in the state, we can access it in our JSX template by saying
this.state.counter

Image description

DON’T MUTATE THE STATE DIRECTLY, use setState

Image description

But there can be a problem, consider this …

Image description

setState does not always immediately update the component. It may batch or defer the update until later. Both the setState calls are enqueued when the value of counter is 0 thus causing the problem.

Let’s solve the above problem.

Image description

Use setState with callback because it is guaranteed to fire after the update has been applied. So first counter gets incremented by 1 by first setState call, once it is done, the counter is then incremented to 2. This update is done in a synchronous manner.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs

React.js – Understanding JSX

Hey guys 👋🏻,
In this post, let us learn what JSX is in React and why it is important for us as React developers to understand it.

Image description

In this post, let us understand

✔ What is JSX ?
✔ Example of JSX
✔ JSX code being equivalent to React.createElement calls.
✔ JSX Restrictions

What is JSX ?

JSX is a syntax extension to JavaScript. It is used to write HTMLish code in JavaScript files which later gets transpiled to normal JavaScript by our development workflow.

Example of JSX

Image description

In the above example, you can see we are returning HTMLish kind of code from our component function. personName is a variable that we are interpolating right inside the template of our component. This in the end gets transpiled to JavaScript.

Before Transpilation

Image description

After Transpilation

Image description

JSX code is nothing but multiple calls to the React.createElement method to build up the HTML for our component.

JSX Restrictions

  1. It allows us to write HTMLish code that we write in JavaScript files.
  2. It enforces restrictions on some keywords that we cannot use like classfor etc that are reserved keywords in JavaScript. We have equivalents for them though.
  3. JSX expression must have exactly one root element and it is under this root element that you nest your JSX code.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs

A Brief Introduction to React.js

Hey everyone 👋🏻,

In this article, let us cover a brief introduction to React.js

Introduction

Image description

React is an open source, front-end JavaScript Library for building modern sleek user interfaces.

It is maintained by Facebook. It is used to create SPAs.

Why React ?

  1. Uses component based architecture to structure your application.
  2. Allows you to write reusable components that can be used across different applications
  3. Easy to learn
  4. Ensures stable code.

Features of React

  1. Optimization of code using a complex development workflow already done for us.
  2. Writing HTMLish Code in JavaScript files using JSX.
  3. Faster rendering because of Virtual DOM.

Disadvantages of React

Not a complete framework
Compared to Angular which is like a kitchen of tools that has everything built in, React depends on a lot of other external libraries that glue with it for creating modern frontends.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

The credits for the vectors used in above articles goes to Vecteezy :
Web Developer Vectors by Vecteezy

Categories
javascript reactjs

What is REST API ?

✨What is REST API ? 

Alt Text

Hey everyone ??,

In this article, let us learn about one of the most important concepts that you as a backend developer must have a solid knowledge of (because anyways working with an API is a big part of your jobs) and that is REST APIs

REST APIs

Cover image for What is a REST API ?

Actual definition:

“”
Representational state transfer (REST) is a software architectural style that was created to guide the design and development of the architecture for the World Wide Web. REST defines a set of constraints for how the architecture of an Internet-scale distributed hypermedia system, such as the Web, should behave. The REST architectural style emphasises the scalability of interactions between components, uniform interfaces, independent deployment of components, and the creation of a layered architecture to facilitate caching components to reduce user-perceived latency, enforce security, and encapsulate legacy systems.
“”

Now you must be wondering : “What the heck does this mean ?”

Alt Text

Anyways, let us make it super simple and understand what a REST API is piece by piece.

Now before we understand why we use a REST API, we first need to understand what problems does it solve ?

REST APIs are there to solve one problem you can say that not every frontend (UI) requires HTML pages. Not every UI wants your server code to generate HTML pages which effectively is the UI.
Think about mobile apps these apps typically do not work with server side rendered HTML code. They do not need a templating language on server side to render the HTML code because you use a rich suite of prebuilt libraries for UI provided by Google or Apple to build your UI in the respective IDEs of these programming languages.

Alt Text

You build these User Interfaces totally decoupled from your server side logic. You don’t want HTML code because you can’t really render it there. Obviously you have browsers in your phone and that will render HTML pages.

But most of the applications do not use HTML to build their user interfaces but the tools that are provided by Google or by Apple and then you only need data to fill these user interfaces to life.

For building these amazing and sleek looking user interfaces on the frontend we have frontend technologies like React, Angular, Vue etc.

Alt Text

So we have a frontend that is decoupled from a certain backend logic like Google Maps (Server) and we only exchange data because we don’t need the HTML code but just the data. We built the User Interface on our own. So we just need a backend server that can typically serve us just the data that we need and then we can easily fabricate our user interfaces as per our requirements.
So, this in essence is the core idea behind the REST APIs.

Alt Text

REST stands for Representational State Transfer which means
that we transfer data (some form of state you could say) instead of user interfaces. We just want our server to send us data and we leave it to our client side app be it a mobile application or be it a single page application to do whatever it wants to do with this data. Thus in traditional web applications we rendered the views on the server side using templating engines and handled both the data and the UI . This is not bad at all it is a common pattern for a lot of web applications

Traditional Web Apps and REST APIs – ONLY THE RESPONSE DATA DIFFERS

Alt Text

Often traditional web applications and the REST APIs are seen as totally two different things. They are not, they only differ in the response and the kind of data that you expect but they don’t differ at the server besides the fact that you do not render
the view there on the server. Here we use all knowledge that we gathered we only fine tune the data handling and finally deliver it to the client in the format in which it is required by the client.

A MAGNIFIED AND CRYSTAL CLEAR PICTURE OF THE REST APIs

Alt Text

So consider this scenario where we have our client (a mobile app, SPA) and then we have our server on which we build our backend REST API.

Now one possible advantage of this can be that we can make one and the same API for handling multiple clients and this is possible because both our mobile apps and web apps rely on the same data source, right. In fact, both the apps are same and consume the same data source. The only difference could be on how they present this data in their user interfaces.

Contrary to this, we can also have kind of a traditional application which just needs our service APIs. And in all such applications it is the data which is exchanged between the client and the server.

WHAT FORMAT DO WE EXCHANGE THE DATA IN

Some of the common formats that we most likely see are :
1.HTML
2.XML
3.JSON etc.

So there are different kinds of data that we can attach to the request and the response objects. So we can send plain text, XML or we could even send JSON.

There are different kinds of data that we can attach to the
request and the response objects. We can send plain text,XML or we could send JSON.

XML

Alt Text

Introduction

React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications. In this article, let us see some cool projects that you can make to make the process of learning React extremely easy.

It looks a lot like HTML. XML allows us to use any tags. It allows us to send any data and does not make assumptions about the user interface because it is not parsable by browsers. They are user defined elements.
These are machine readable but relatively verbose but you can define clear structures here. Here an XML parser is needed because node traversal in XML node tree is kind of a challenge in itself. So in essence you need an XML parser to efficiently parse the XML data.

JSON

Alt Text

JSON is kind of a defacto standard for data interchange in web applications. Here also we work on just the data and the JSON does not make assumptions about the user interface. It is machine readable and a bit more concise than XML and can easily be converted to Javascript.
This is a huge plus when working with Node.js on the server and JavaScript on the browser. It is the most common format used in any of the APIs that you are communicating with these days.

Routing and HTTP methods

Now we know our web works on request and response cycle. So we have a client that interacts with the server in form of requests and response to get the data that it needs and more. Check my video on Client Server Architecture to know more regarding this :

So this is how we communicate with our server. In the REST World, these communications take place in form of paths which are known as API Endpoints

API ENDPOINT = ANY COMBINATION OF THE HTTP METHOD AND THE RESPECTIVE PATH
These are the endpoints that we define on our REST API and we
also define some logic that should get fired when such a request reaches our end point.

HTTP METHODS

More than just GET AND POST(These are only when we are working with links and forms), we have other HTTP methods as well that the browser natively knows of. So here is a short summary of the HTTP methods that our request client has access to.

GET – Get a resource from the server

POST – Post a resource to the server which is responsible for creating or appending a resource to an already existing array of resources so to say.

PUT – Put a resource onto the server(i.e create or overwrite a resource). Post should never overwrite an existing resource though it can do but it is not recommended

PATCH – Update parts of the existing resource on the server(not overwriting the entire resource but the parts of it)

DELETE – Delete a resource on the server

OPTIONS – Determine whether follow up request is allowed(sent automatically by the browser)
This is automatically sent by the browser to find if the next request it tries to do is allowed or not.
It is the best practice to use these methods in this way though you can do anything you want

This way any one who uses your API clearly knows what to expect for a given method

REST PRINCIPLES

Alt Text

1. Uniform interface, clearly defined API endpoints with clearly defined request and response structures
IOW, your API should be predictable and also it should be well documented if it is open to the public.
So people should know what data your API expects and what data it gives back.

2. Stateless interactions
When building the server and the client, the server and the client are totally decoupled and they don’t share a common history
,every request is handled separately. And therefore no sessions can be used since no connection history is shared among the client
and the server. Every incoming request is treated as if no prior request was sent. Server has a look on every request on its own. It does not store a session about the client.

You can just build an API and open it to the public and just present the documentation of its usage to the client.
You don’t care at all about the clients. You just say here is the endpoints I have ,here is the data you get for each of the well-defined endpoints.
So in essence, we have a strong decoupling between the client and the server even if they were to run on the same server because we are building the API for our application so that they work independently from each other and just exchange data without sharing the connection history.

3.Cacheable

Alt Text

You could send the client some response headers telling the client for how long the response is valid.
Servers may set caching headers to allow the client to cache responses.

4.Client-Server
Client and Server are separated,client is not concerned with persistent data storage.It is the responsibility of the server.

5.Layered System

Alt Text

As a client we send a request to a server, we can’t rely on that server we sent it to to immediately handle the request, the server may handle the request to other server or distribute it to other servers if it is busy.
Ultimately we care about the data that we get back which should follow the structure that was defined by the API.

6.Code on Demand

Alt Text

REST API could also for some end points transfer executable code to the client.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

REST API could also for some end points transfer executable code to the client.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text