JSFiddle - React, Tailwind, and code Playground

HTML

<div id="pagina">
	<header>Cabeçalho</header>
    <div class="sidebar">Sidebar</div>
	<footer>Footer</footer>
</div>

CSS

* {
    margin: 0px;
    padding: 0px;
}
header, footer{
	height: 150px;
	text-align: center;
	background-color: #88b;
	width: 100%;
}
#pagina {
    width: 100%;
    height: 2000px;
    position: relative;
}
.sidebar {
    float: right;
    width: 50px;
    height: 400px;
    right: 0px;
	background-color: #ccf;
}
footer {
    position: absolute;
    bottom: 0px;
}

.fixed {
    position: fixed;
}

JavaScript

var sidebar = jQuery('.sidebar');
var header = jQuery('header').height();
var alturaFooter = jQuery('footer').height();
var alturaPagina = jQuery('#pagina').height();
var alturaSidebar = sidebar.height();

jQuery(window).scroll(function () {

    // colar o sidebar
    var threshold = 20;
    var scroll = jQuery(window).scrollTop();
    if (scroll >= header) sidebar.addClass('fixed');
    else sidebar.removeClass('fixed');

    // seguir o footer
    if (scroll + alturaSidebar > alturaPagina - alturaFooter) sidebar.css('top', alturaPagina - scroll - alturaSidebar - alturaFooter);
    else sidebar.css('top', 0);

});