DEV Community

Cover image for What is the difference between Library vs Framework?
Rohit Singh Rana
Rohit Singh Rana

Posted on

What is the difference between Library vs Framework?

While the terms Library and Framework may sound similar, they both work differently.

Many people use these two words interchangeably without knowing the profound meaning behind them.

Before we dig into the key differences between Library and Framework, let's look at the common purpose that they both serve.

Both Library and Framework are code written by some developer to solve a complicated problem efficiently.

They both give you an excellent approach to write DRY (don't repeat yourself) code.

Their purpose was to increase the reusability of the code so that you can use the same piece of code or functions again in your various project.

What is Library?

A Library is a set of code that was previously written by a developer that you can call when you are building your project.

In Library, you import or call specific methods that you need for your project.

In simple words, a bunch of code packed together that can be used repeatedly is known as Library.

Reusability is one of the main reasons to use libraries.

Let's understand this more clearly with the help of an example.

Think of you as a carpenter who needs to build a table.

Now, you can build a table without the help of tools, but it's time-consuming and a long process.

Whereas, if you choose the correct tools, you'll be able to build a table more quickly and that too without any hardship.

Think of here tools as a library. You can write your program without them.

But it will be a long process, and chances are your program will get buggy, while if you use Library, it'll be much easier for you to work with the program.

For example, if you use the in-built JavaScript fetch () method to fetch the data from API and you feel that it's not the ideal solution.

Then you can use Axios Library for the same purpose to make your work easier.

axios.post('/login', {
  firstName: 'Monica',
  lastName: 'robinson '
})
.then((response) => {
  console.log(response);
}, (error) => {
  console.log(error);
});

Enter fullscreen mode Exit fullscreen mode

Some common examples of Library are:

React

React is a JavaScript library for building user interfaces.

Redux

Redux is an open-source JavaScript library for managing application state.
It's most commonly used with React

Three.js

It's another super cool JavaScript library used to create and display 3d computer graphics.

Lodash

Lodash is a JavaScript library that provides utility functions for common programming tasks.

It's more of a productivity kit in node.js

jQuery

jQuery is a JavaScript library that does the things like event handling and HTML document manipulation.

What is Framework?

A framework is a supporting structure that gives shape to your code.

In the Framework, you have to fill the structure accordingly with your code.

There is a specific structure for a particular framework that you have to follow, and it's generally more restrictive than Library.

One thing to remember here is that frameworks sometimes get quite large, so they may also use the Library.

But the Framework doesn't necessarily have to use Library.

Let's get back to our carpenter and table example for a better understanding of the Framework.

Here, if you want to build a table, then you need a model or skeleton for how the table looks, like the table has four legs and a top slab.

Now, this is the core structure of the table and you have to work accordingly to build the table.

Similar to this, Framework also provides the structure, and you have to write the code accordingly.

Let's take the example of Express and understand the restrictive nature of the Framework.

var express = require('express')
var app = express()


app.get('/', function (req, res) {
  res.send('welcome to dev.to!! ')
})
app.post('/', function (req, res) {
  res.send('POST request to the dev.to homepage')
})


Enter fullscreen mode Exit fullscreen mode

Here express is designed in such a way that it is going to look only for specific methods (get/post) and specific parameters.

You can't name the methods whatever you want to, and you have to name the methods as per the documentation.

Some common examples of Framework are:

Angular

Angular is a JavaScript framework for web and mobile development.

Django

Django is a fully featured server-side web framework written in
Python.

Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Rails

Rails is a web application development framework written in the Ruby programming language.

Spring

Spring Framework is an open-source framework for building web applications with Java as a programming language.

Key Difference between Library vs Framework

The main key difference between the Library and Framework is something known as inversion of control.

Let's understand this inversion of control more in detail.

When you import a library, you have to call the specific methods or functions of your choice so, and it's up to you when and where to call the Library.

Here, you are in charge of flow.

On the other hand, Framework itself makes a call to your code and provide you with some space to write down details.

So, while using framework your framework is in charge of flow.

In Library, your code is going to call the Library whereas, in Framework, your code is being called by Framework.

Conclusion

I know it's getting too confusing but stay with me. I'll end this with one last crucial point.

Here is a simple thing to remember Framework is often more restrictive and generally have a more set of rules.

Whereas, Library is not bounded by many rules.

I hope you get a broader perspective of what's the difference between Library and Framework.

If you find my work interesting and worth reading you can appreciate me on Twitter and LinkedIn.

All kinds of Feedback are welcomed in comments.

Top comments (24)

Collapse
 
peerreynders profile image
peerreynders • Edited

Some common examples of Library are: React

yet later:

In the Framework, you have to fill the structure accordingly with your code.

Creating a React component is filling that structure (even as a function component).

The main key difference between the Library and Framework is something known as inversion of control.

Correct.
Your React components are managed/invoked by React. By calling ReactDOM.render() you hand over the UI/main thread to React. Past that point the components may use the tooling provided by React - but the components only get control when React decides to give them control.

For more details React is a (view component) framework.

One could argue that by calling itself a library React has greatly contributed to the library vs framework confusion.

Collapse
 
jackmellis profile image
Jack

This. I've never understood the insistence that react is not a framework as it totally is. Maybe it was originally a library, but the fact that we now build "react apps" is an obvious sign that it's a framework.

To me a framework is something that drives and control a major part of your code, whereas a library just helps you in writing your code.

For the same reasons I always feel like express is more library than framework. Essentially its just a thin wrapper around the http module, and aside from setting up routes, it has no control or interest in how the rest of your app works

Collapse
 
peerreynders profile image
peerreynders • Edited

For the same reasons I always feel like express is more library than framework.

1988 Johnson & Foote:

The methods supplied by the user tailor the generic algorithms defined in the framework for a particular application.

Looking at the express Hello World:

  • express() returns a generic express server.
  • app.get() "tailors" that generic server with user code - which will only be invoked by the express server.
  • app.listen() starts that generic server with the user code that "tailors" its operation ...

The framework often plays the role of the main program in coordinating and sequencing application activity

... which is exactly what app.listen() accomplishes. So express ticks all the boxes for a framework - while the main thread configures the generic server, once running, the generic server calls all the user code that was supplied via configuration.

It really comes down to:

  • If your code calls it, it's a library.
  • If it calls your code, it's a framework.

Off course by that definition the http module itself is a "framework" ...
node.js Hello world
... because the module "plays the role of the main program" and the module "calls the user code".

This just illustrates that a "framework" doesn't have to be big, complex or "all batteries included".

Collapse
 
jonahgeek profile image
Jonathan Mwebaze

"Something that drives and controls a major part of your code", don't you think this makes create-react-app the framework and reactjs just a library, just like react-scripts, react-dom, redux etc... We don't build react apps, we use react to build applications. React is just part of it, just like react-dom or even react-router-dom

Thread Thread
 
peerreynders profile image
peerreynders

TL;DR: "Framework" !== "Application Framework"

See my other comment.

React is the core that is responsible for "the operation in the manner of a framework" - orchestrating the application activities and only delegating to user code via inversion of control.

React components (user code) aren't being run by the event loop but by React.

So while React may look like it's just a layer between the components and the JavaScript runtime it's actually React running (calling) the components - components don't use React unless React calls them first.

Collapse
 
snyntakk404 profile image
snyntakk404

React is more of a mix of both framework and library. It has the key pieces of a library but contains concepts of a framework. Thus I classify it as both with it leaning towards framework. This was a great article but it some editing with the examples.

Collapse
 
theinterviewsage profile image
The Interview Sage

Great Post! Thanks for sharing!

Collapse
 
vonheikemen profile image
Heiker

The way I see it, if you let React become the center of the universe (meaning your app/project), you got yourself a framework. I believe strongly opinionated frameworks are not the only kind of framework.

 
peerreynders profile image
peerreynders • Edited

What's the concrete thing that from your Point of view makes React a framework and µhtml a library?

  • µhtml: What calls the update() function ? update(START) - i.e. user code. By extension html and render are only called by user code.
  • React: What calls the App() component? React. render(h(App), document.querySelector('.js-root')); only hands over the component to React - it's up to React to invoke it. By extension any code inside of App() (the "user code") only runs when React wants it to.

As I wrote in my second comment:

  • If your code calls it, it's a library.
  • If it calls your code, it's a framework.
Collapse
 
peerreynders profile image
peerreynders • Edited

From your point of view, React would have to give you control over the VDOM trough functions that you'll call to "be a library", which is kinda ludicrous.

I fail to see how that is in any way ludricrous. Call it a VDOM framework then.

What exactly does the JSX <p>{count}</p> do? It desugars to:

React.createElement('p', null, count);
Enter fullscreen mode Exit fullscreen mode

So a React (functional) component's return value is a ReactElement.

2005 Martin Fowler: InversionOfControl

A framework embodies some abstract design, with more behavior built in. In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points.

So while functional components have eliminated the need to subclass React.Component, functional components are "plugged into" React because that is how React creates the component tree and each and every functional component returns a ReactElement - a type that is specific to React and created by React via React.createElement. And the relevant location for that ReactElement is determined by the location of the component instance within the component tree.

A simple working example:

<!doctype html>
<html lang="eng">
  <head>
    <meta charset="utf-8"/>
    <title>React is a Framework</title>
  </head>
  <body>
    <main class="js-root"></main>
    <script src="https://unpkg.com/react@latest/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@latest/umd/react-dom.production.min.js"></script>
    <script>
     (function () {
       // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L276-L279
       //
       // function createElement<P extends {}>(
       //   type: FunctionComponent<P>,
       //   props?: Attributes & P | null,
       //   ...children: ReactNode[]
       // ): FunctionComponentElement<P>;
       //
       //
       // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L158-L160
       //
       // interface FunctionComponentElement<P> extends ReactElement<P, FunctionComponent<P>> {
       //   ref?: 'ref' extends keyof P ? P extends { ref?: infer R } ? R : never : never;
       // }
       //
       const render = ReactDOM.render;
       const h = React.createElement;
       const useState = React.useState;
       const useEffect = React.useEffect;

       // --- BEGIN user supplied component oriented application
       function App(_props) {
         const count = useCount(0);
         return h('p', null, count);
       }

       const MS_PER_COUNT = 1000;
       const START = document.timeline.currentTime;
       const increment = (value) => value + 1;

       function useCount() {
         const [_dirty, setDirty] = useState(0);
         // Base `count` on a fresh timestamp
         const count = Math.floor((performance.now() - START) / MS_PER_COUNT);

         useEffect(() => {
           const refresh = () => setDirty(increment);
           // Base `delay` on a fresh timestamp
           const delay = (count + 1) * MS_PER_COUNT - (performance.now() - START);
           const timeoutID = setTimeout(refresh, delay);
           return () => clearTimeout(timeoutID);
         });

         return count;
       }

       // --- END application
       // "React is your Application": handing over application to React
       render(h(App), document.querySelector('.js-root'));
     })();
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

That last render statement is where the "inversion of control" kicks in. render is the framework function that "plays the role of the main program".

Contrast that to µhtml which is a library:

<!doctype html>
<html lang="eng">
  <head>
    <meta charset="utf-8"/>
    <title>µhtml is a Library</title>
  </head>
  <body>
    <main class="js-root"></main>
    <script type="module">
     import { render, html } from 'https://unpkg.com/uhtml?module';

     const MS_PER_COUNT = 1000;
     const START = document.timeline.currentTime;
     const root = document.querySelector('.js-root');

     function update(timestamp) {
       const elapsed = timestamp - START;
       const count = Math.floor(elapsed / MS_PER_COUNT);
       render(root, html`<p>${count}</p>`);
       const refresh = () => requestAnimationFrame(update);
       const delay = (count + 1) * MS_PER_COUNT - elapsed;
       setTimeout(refresh, delay);
     }

     update(START);
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

html is a tagged template which returns an object that is designed to produce something that extends HTMLElement a platform type (not a framework type). render is a convenience function that attaches that DOM element instance to the indicated platform location.
In terms of the script the final statement invokes a user function (not a framework function) - so the user code is always running the show - so there is no framework in control here.

Interestingly µhtml is the foundation for µland - a React-style framework:

<!doctype html>
<html lang="eng">
  <head>
    <meta charset="utf-8"/>
    <title>µland is a Framework</title>
  </head>
  <body>
    <main class="js-root"></main>
    <script type="module">
     import {
       Component,
       render,
       html,
       useState,
       useEffect,
     } from 'https://unpkg.com/uland?module';

     // --- BEGIN user supplied component oriented application
     const App = Component((initialState) => {
       const count = useCount(initialState);
       return html`<p>${count}</p>`;
     });

     const MS_PER_COUNT = 1000;
     const START = document.timeline.currentTime;
     const increment = (value) => value + 1;

     function useCount() {
       const [_dirty, setDirty] = useState(0);
       // Base count on a fresh timestamp
       const count = Math.floor((performance.now() - START) / MS_PER_COUNT);

       useEffect(() => {
         const refresh = () => setDirty(increment);
         const delay = (count + 1) * MS_PER_COUNT - (performance.now() - START);
         const timeoutID = setTimeout(refresh, delay);
         return () => clearTimeout(timeoutID);
       });

       return count;
     }

     // --- END application
     // Handing over application to µland
     render(document.querySelector('.js-root'), App(0));
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • note how the user code is wrapped in a framework specific function type (via Component)
  • the final statement uses render, a framework function, exercising "inversion of control".

you have actual frameworks like Angular.

Why is it that people associate "framework" with size and complexity? The criteria for categorizing software as a "framework" were established long before either Angular or React were created. While the statement "React isn't an application framework like Angular" may be correct that in no way implies that React isn't a framework in its own right.

Why is it that people act as if the sky is going to fall on their head if they were to utter "React is a framework"?

 
peerreynders profile image
peerreynders

Isn't µhtml calling my component as well?

The point is by the time render() returns nothing of µhtml is left of the call stack. The user code is in complete control.

The difference is that React's render doesn't make you do the update, while µhtml does.

The relevant difference is that with React your code calls render() once during the entire lifetime of the application session and React remains active for the remainder of that session - orchestrating all actions that the application takes from that point on (i.e. React is in charge).

µhtml's render() has to be called whenever your code wants to patch the DOM; so render() is called many times during the application's lifetime - and when render() returns your code is completely in the driver seat - not µhtml.

I mean in the FE generally we consider something a Framework when it comes bundled with an answer to every question (routing, testing, components, and so on).

What you are describing is an application framework. Not all frameworks are application frameworks. So if you are correct that means that in FE development application framework has been contracted to framework narrowing the meaning of the term significantly.

Still, I guess we can close it in a "we agree to disagree".

At this point your perspective seems to be:

  • it's a framework if it's an application framework
  • otherwise it's a library irrespective of the fact whether or not it operates in the manner of a framework.

My perspective is:

  • it's a framework if it remains active for the entire application session lifetime and orchestrates user code via inversion of control.
  • a library provides capabilities that abstracts certain details away but these capabilities are only temporarily and directly invoked by the user code; after the capability returns the user code is completely in charge again to orchestrate the application's actions as it deems fit.

I think at this point it's clear which view I find more obvious and less confusing.

React ... is an extremely simple and unopinionated one, that only takes care of your interactions with the DOM.

Calling React unopinionated is in my view misleading at best. It certainly is less opinionated than Angular but that isn't the same thing as being unopinionated. In fact choosing React as your abstraction has a significant impact on your client side solution architecture.

Redux maintainer Mark Erikson made an astute observation:

I've noted that React devs can often be classified into two groups: those who see the React tree as their app / have a "component-centric" view, and those who view their state / logic as their app / have an "app-centric" view.

The majority of Kent C. Dodds's article Application State Management with React explores the component-centric approach which goes beyond "taking care of interactions with the DOM" - it essentially uses React as if it was an application framework to the point that "React is your Application".

The "app-centric" approach tries to separate the application from React, narrowing React's responsibilities to just "taking care of interactions with the DOM". However as soon as you use an integration like React-Redux you are coupling your React code with the way Redux operates, trading away the opportunity to cleanly separate your UI from the client-side aspect of your application (and as David Khourshid points out Redux has its own set of trade offs).

In UI As An Afterthought Michel Weststrate discusses how he builds the client-side application around MobX rather than having the UI abstraction dictate the structure of the application (a modern take on Segregated DOM). Having a clear boundary between React (the UI) and the rest of the client-side application is important to use web workers effectively.

The point is that you have to be pretty disciplined and determined (i.e. it's not the path of least resistance) if you want React to just "take care of interactions with the DOM".

 
peerreynders profile image
peerreynders • Edited

I generally try out everything made by WebReflection because he is a fantastic developer

And he never tires of pointing out to everybody that React is a costly abstraction (1, 2, 3, 4, 5, 6, 7, 8).

but your example with µhtml you're just calling render in a fixed interval, but that render expects the output of html,

Which is exactly what one does when rendering with a library.

React is just making that "interval" for you. Does that turn it into a framework from your PoV?

The point is that a functional component is nothing but a glorified (but "tailored") render() function.

But the difference is that in the case of µhtml the user code is always in control - html and render are simply helper functions for generating and placing the DOM nodes so that the user code doesn't have to deal with them directly making the user code more declarative than manipulating the DOM manually.

In React the user code doesn't call function components ("tailored render functions"); the function components are user code which are handed over to React which then invokes them as it deems fit - that is what makes React a framework.

That said I have yet to run across a VDOM library - all VDOM abstractions I have encountered are operating in the manner of a framework.

there is a great library by developit

I'm familiar with Jason Miller's work.

Collapse
 
acahuiche profile image
Alberto Cahuiche

Muy bien explicado, gracias por la información

Collapse
 
kalashin1 profile image
Kinanee Samson

thanks for the update pal, and I agree that react is more of a library than of a framework.

Collapse
 
snyntakk404 profile image
snyntakk404

That is a great explanation of 2 key concepts for beginners!

Collapse
 
rohitrana profile image
Rohit Singh Rana

Thanks!

Some comments have been hidden by the post's author - find out more