2025-03-19 23:46:57
Custom hooks have transformed how I write and manage logic in React applications.
They allow me to extract reusable functionality from components, making my code cleaner and easier to test.
In this post, I’ll share my journey in working with custom hooks, explain what they are and how they work, and provide a step-by-step guide to creating your own.
Custom hooks are functions in React that let you combine and share logic between components.
They take advantage of React’s built-in hooks, like useState
and useEffect
, to help manage stateful logic outside of your component tree.
This means that if you have a piece of logic you want to use in multiple places, you can wrap it in a custom hook instead of duplicating code.
For example, if I need to fetch data from an API in several components, I can create a custom hook that handles fetching, error management, and loading state.
This approach not only reduces duplication but also makes your components less cluttered.
Custom hooks are important for several reasons:
React’s official documentation covers hooks in detail, and I highly recommend checking out the React Hooks documentation for more insights.
Creating a custom hook is as simple as writing a regular JavaScript function that starts with the word “use.”
This naming convention tells React that the function follows the rules of hooks. Let’s walk through a basic example.
Imagine I need a hook to manage the window size for a responsive design. Here’s a step-by-step guide:
Set Up Your Hook:
Create a new function and start its name with “use.” In this case, I’ll call it useWindowSize
.
Initialize State:
Use React’s useState
to keep track of the window dimensions.
Add Event Listener:
Use useEffect
to set up an event listener that updates the state when the window size changes.
Clean Up:
Return a cleanup function from useEffect
to remove the event listener when the component unmounts.
Here’s a code snippet to illustrate:
import { useState, useEffect } from 'react';
function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
// Cleanup the event listener on component unmount
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
export default useWindowSize;
In this example, useWindowSize
returns an object with the current width and height of the window.
I can now import this hook into any component and use it to build responsive features without rewriting the resize logic.
Over time, I’ve learned a few best practices for working with custom hooks:
If you’d like more detailed guidelines, I suggest checking out some articles on testing and documenting React hooks, such as this guide on testing custom hooks by Kent C. Dodds.
What makes custom hooks different from regular functions?
While custom hooks are just JavaScript functions, they follow special rules. They can only be called at the top level of a component or another hook. This ensures that the hook order remains consistent on every render.
Can I use multiple custom hooks in a single component?
Absolutely. You can use as many hooks as you need in a component. Custom hooks help in breaking down complex logic into manageable pieces.
Are custom hooks only for state management?
No, custom hooks can be used for anything that requires shared logic. This includes fetching data, handling subscriptions, integrating with third-party libraries, and more.
What should I do if a custom hook becomes too complex?
If a hook starts handling too many responsibilities, it might be a sign that you need to refactor. Consider splitting the hook into smaller hooks that each manage a single aspect of the logic.
How do I know when to create a custom hook?
If you notice the same logic repeated in multiple components, or if you want to isolate complex logic for easier testing and readability, it might be time to create a custom hook.
If you want to dive deeper into custom hooks and React, here are a few resources that I’ve found useful:
React Official Documentation:
React Hooks
The official docs provide a great introduction and reference for all hooks, including custom ones.
Articles and Tutorials:
Building Your Own Hooks in React
This tutorial on DigitalOcean walks you through creating and using custom hooks in various scenarios.
Video Tutorials:
There are several video series on platforms like YouTube that explain custom hooks step by step. I recommend searching for “React custom hooks tutorial” to find content that matches your learning style.
Community Discussions:
Platforms like Stack Overflow and GitHub issues can provide insights into how other developers solve common problems with custom hooks. For a quick discussion and tips, visiting Reactiflux on Discord can also be very helpful.
Custom hooks are a fantastic way to keep my React projects organized and maintainable.
They allow me to isolate and reuse logic, reduce redundancy, and improve the overall clarity of my code.
After writing and refining my custom hooks, I’ve found that even the most complex features become easier to manage and test.
Using hooks like useWindowSize
has not only saved me time but also improved the user experience of my applications by ensuring responsive and robust performance.
I hope this guide has given you a clear picture of how to build and use custom hooks in React.
Have you already experimented with custom hooks, or do you have ideas on how they could simplify your React projects?
2025-03-19 23:44:01
I often get asked about managing configuration settings in React projects. Using an env file is one of the simplest ways to handle this.
In this article, I'll walk you through what an env file is, why it's useful, and how to set it up in your React JS project.
An env file is a plain text file that stores environment-specific settings.
These settings can include API keys, URLs, and other configuration details that your project needs to run. The idea is to separate these details from your main codebase.
This separation helps keep sensitive information safe and makes your code easier to manage.
In a React project—especially one created with Create React App—using an env file means you can easily switch between different environments, such as development and production.
By using a dedicated file, I can adjust configurations without changing the code itself.
There are several reasons to use an env file:
Security: Storing secrets like API keys in an env file helps keep them out of your code repository. This practice can reduce the risk of accidentally exposing sensitive data.
Flexibility: With an env file, you can change settings without touching your code. For example, you might have different API endpoints for development and production. An env file makes it easy to switch between these.
Organization: By isolating configuration details from code, your project stays cleaner and easier to read.
Consistency: Following best practices such as the 12-Factor App method ensures that my project can scale better and integrate smoothly with various services.
You can read more about these practices on the 12-Factor App website.
I’ve seen many projects benefit from this approach. A survey by the Stack Overflow Developer Survey 2023 noted that a large number of developers favor using environment variables to keep configurations separate from the code. This method is a key part of many modern development workflows.
Now, let’s get into the practical side of things. Here’s how you can create and use an env file in your React JS project:
Start by creating a file called .env
in the root directory of your project. This file will hold all your environment variables. The file name must be exactly .env
—no extra characters or extensions.
Inside the .env
file, write your variables in the following format:
REACT_APP_API_URL=https://api.example.com
REACT_APP_API_KEY=your-api-key-here
A couple of things to note:
REACT_APP_
. This is how the build process knows which variables to expose.Once your variables are set up, you can access them in your React components like this:
const apiUrl = process.env.REACT_APP_API_URL;
console.log('API URL:', apiUrl);
This code snippet fetches the value of REACT_APP_API_URL
and logs it. You can use these variables anywhere in your project.
After you add or modify your env file, you need to restart your development server. This step is crucial because changes in the env file will not be picked up until you do so.
It’s important to ensure that your env file doesn’t end up in your public repository. To avoid this, add .env
to your .gitignore
file. This simple step helps keep your sensitive data secure.
Here are a few tips to make the process smoother:
REACT_APP_
prefix for your variables. If you forget this, Create React App will ignore the variable..env.development
and .env.production
. This helps keep configurations organized..gitignore
is an essential habit.For more detailed instructions and examples, check out the official Create React App documentation on adding custom environment variables.
What is an env file?
An env file is a simple text file that stores environment-specific configuration variables. It helps keep settings separate from your main code.
Why do I need to use the prefix REACT_APP_
?
This prefix is required by Create React App to expose the variable to your application. Without it, the variable won’t be accessible in your code.
Do I need to restart my server after changing the env file?
Yes, changes to the env file require you to restart the development server so the new variables are loaded.
Can I use multiple env files?
Absolutely. You can have different env files for different environments, such as .env.development
and .env.production
, to better manage your project settings.
Is it safe to commit my env file to version control?
Generally, no. It’s best to add the env file to your .gitignore
to keep sensitive information out of your repository.
If you’d like to explore more on this topic, here are some helpful resources:
Using an env file in your React JS project is a practical approach to manage your app’s configuration.
It makes the code cleaner, improves security, and provides the flexibility to switch settings based on your deployment environment.
I have seen many projects benefit from this method, and I’m confident that adopting this practice can help streamline your development process.
I hope this guide has given you a clear understanding of how to create and use an env file in your React project.
The steps I shared are simple to follow and can make a big difference in managing your application’s settings.
With the right approach, you can avoid common pitfalls and enjoy a smoother development experience.
Now, how will you create an env file in your React JS project?
2025-03-19 23:41:45
Back in the day, when I was more actively playing the electric guitar, there was an interesting topic on my favorite guitar forum. Guitarists often add some attachment to the guitar but not to the amp or effects. And you need all of that to make your sound on electric guitar. One guy suggested that it's because we touch the instrument with our hands all the time, its physical connection creating a mental bond. I agree. I've bought and sold amps, effects, cables, and accessories, but my guitars are here to stay. I gave them names.
Do we, software engineers also develop a connection to things we use at work? Personally, not really. As long as it works and gets the job done, we don't touch our code with our hands. We do touch keyboards.
They are the most diversified and opinionated accessories we use. Chassis shapes, switches, keycaps, low—or high-profile... But can they be even more personalized?
Paraphrasing the first Polish encyclopedia, everyone knows how the keyboard looks. If you read this, you probably write fluently on a QWERTY row staggered keyboard without looking. We all grow up with those, writing school essays, typing The Sims cheat codes, and making angry comments online.
But then I saw this:
in the YT video
And I had 2 thoughts: incredible shoot with the terminal in the middle… the middle of what??? What is this typing device? Because it's not a regular keyboard?
It appears to be Dygma Defy. Interesting; I've never heard of those before. But 369$ for the base model is successfully discouraging me. Maybe there are cheaper options? Not really... and there are works of art like Naya that can go around 1000$, absolute units like Kinesis or more common ErgoDox EZ, which is still over 300$. There is none aftermarket where I live for those, so I can't even try them out. And I don't want to spend that much on something I might not like.
I have to admit, I like the idea of a different key layout; using column stagger rather than row stagger seems more natural.
It is also healthier for the hand. The idea is to make fingers move up and down, not diagonally. Staggered columns reflect differences in finger length. Ideally, there would be a single row above and below the home row, so fingers do not have to stretch and hands move.
But it means having fewer keys overall—no function keys, number keys, or arrows. How can it work for a programmer with wrist-bending IDE shortcuts?
I already own a slightly modded Keychron K2 (tape mod, sound damping, lubed switches, new keycaps) and a K11 low profile with Alice layout. I don't need a new keyboard with 2 nice ones and working, and I don't want to spend so much on that.
Wait. I'm an engineer. I have a 3D printer and a soldering iron. How hard can it be?
It's doable with what I know and have at home, or can easily get online. That is all I needed to start researching some Open Source projects. And boy, I've found so much more. A whole community of keyboard builders that, for free, share their 3d designs, board projects, software, firmware, tips, and tricks. There is a website that gathers intel about all that.
The catalog of keyboard switch sounds, popularity, and the whole DB of switches data. Do you want a lubed tactile cherry switch? There is a search with filters. You can then pick what fits your desired pressure force.
Designs range from pretty standard keyboards, through ortho-linear and split, to ergonomically shaped, or some monsters with the trackballs on the side or in the middle. Why not? There is no limit as long as it works for you. Check yourself!
Here are some of the most known designs:
I did some reading and gathered what I wanted to make and what I was comfortable doing. The number of options and places to fail makes it a bit more complex than a lego set, or even predefined keyboard kit. Let's do iterations rather than jump into deep water to sink. The MVP is a macropad, a small keyboard with a few keys, to get a feel for the switches, keycaps, and the whole process.
I found this hand-wired macropad, which seems just about what I need.
It requires just one cheap Arduino board, 15 switches, and an encoder. Chassis is a simple 3d print, so I don't have to get PhD before starting.
Starting from 3d printing. I'm not experienced yet; I press print, and the printer goes brrr brrr brrr. And I faced some issues:
The problem with clogging had a surprising solution. I use the Creality K1C, a fully enclosed 3D printer. The top cover should be opened when printing PLA, the most common filament. Otherwise, the inside temperature is too high, and the filament can melt too early in the extruder, expanding and clogging it. No, I didn't read the instructions. I said I'm an engineer.
I let the print cool down to solve the problem of sticking to the printer bed. I was too eager to use the model and tried to detach it immediately. Now, I just put it next to the window, where it's colder, and let it cool down for a few minutes. It works like a charm.
I got some post-processing tools, such as sanding paper, a special rotating knife, a hand driller, etc., like for a plastic plane or ship models. They make everything much more manageable.
And better, lighter soldering iron with temperature control. With some extra endings for precision soldering.
I have the chassis printed and screwed down. Well, because I didn't put threads at a 90-degree angle, it doesn't fit perfectly, but it's good enough.
I got some pre-lubed linear switches from Aliexpress. I didn't want to get anything expensive because there is a huge chance I will screw it up. I put them in their places, printed encoder holder, and cap; all good for now.
And understand the pin assignment and electrical schema. The first surprise is that individual keys are not connected to separate pins on the board. It's a matrix of rows and columns. That way, a single board can handle many more keys. Genius. When key is pressed the board gets 2 signals, on row and column and can use it to map it to the key. Because of that, each key has to have a diode soldered in, otherwise the unintended electrical paths could be made when pressing multiple keys.
Switches have 2 pins, and the encoder has 5. The encoder has more functions: button press (handled by 2 pins) and left/right twist (managed by the other 3 pins). I had to check the technical diagram to figure out what goes where. University PTSD is kicking in.
I've watched a few YouTube videos on hand-wiring keyboards (like this one and have somewhat of an idea how it should look like. I'll use diode wires to connect the rows. I've got copper wire, some heat-shrink bands for columns, and some silicon wire (awesome stuff) to connect it all to the board.
I had issues flashing my ProMicro board or putting it into a flash boot state. Eventually, it worked, but not like the official instructions promised. Shorting the RST and GND pins didn't work, but brute force pushing firmware exactly 1s after connecting the USB-C cable to the board did.
The project README wanted me to wire one column to pin E6 and another to pin C6 on the board, but my board has only one pin with number 6.
Official Arduino inputs are different from clones. In the diagram above, it can be described as one of three names. Why make stuff easy, right? It took me about an hour to learn it.
I've put everything together, and it worked!!! I pressed the button, and a digit was sent to my computer. My brother laughed a bit at my soldering skills, but it works, and that's all that matters.
I can make something of a keyboard work. I can print the case, solder it, and flash the board. The next logical step is to create a regular split keyboard.
The number of options is scary. Switch type, case shape, number of keys, wired or wireless, PCB or hand-wired, hot-swap or fixed... So, I decided to not make any decisions and simply build
macropad author designed one.
It was more-less the same, with key matrix and encoders, with additional TRRS (Tip-Ring-Ring-Sleeve) sockets and cable to connect 2 boards.
I couldn't really understand how 2 microcontrollers communicate with each other, send power, and use the same exact software. At the same time, one is the main board connected to a computer, and the other only captures the key presses. And I didn't have to. QMK works like magic here. TRRS wire uses standard jack-jack cable like headphones with a microphone to send 5V, ground, and serial data, leaving 1 wire unused. Both boards use the same pins for that, so plugging the left MAIN board was powering the right one, and the key presses were flowing.
It took me a while to figure out which pin of TRRS goes where. The GitHub repo for the project expects the reader to have some idea of what they are doing.
Checking diagrams again:
Trust me, I'm an engineer. I can do this. I do not know where is pin 1 and why pin 3 is used for ring 1 but at this point I'm too afraid to ask. I chose to believe there is logic there.
I didn't have issues printing and putting the case together this time, thanks to my previous experience with the macropad project. Soldering went better; everything fit inside.
But I used SuperGlue to make TRRS sockets stay in place, which made one of them not work, and I couldn't get it out of the case... so I had to print a new one. No more SuperGlue. Ever.
I also had a problem finding a short enough TRRS cable with both jack connectors having 4 sections and not importing it from Australia. So I bought 3 cheap ones when I saw some, just in case.
Putting everything together took a few evenings. I mostly spent time figuring out missing pieces and soldering 44 individual switches and 2 encoders.
And again, it worked. This whole text was clumsily written on my very own keyboard.
I started spending time with https://www.keybr.com/ to practice writing in the new alien key setup. It's painful—imagine learning to write with your non-dominant hand—but it's also enjoyable. It feels weird and uncomfortable, but there is progress every day, and that's a pleasant feeling. My fingers are actually barely moving, my hands are spread and angled as I feel comfortable. And I can put a coffee mug in the middle. Can your magic keyboard do that?
I've mentioned soldering 44 keys, while standard keyboard has 104. My old Keychrons are 75% and 60% keyboards, but now I have just 40%. And layers. 4 layers containing all I need and still some empty space. You may not be familiar what layers are in keyboard but you are using them anyway, with a shift
key you switch to the upper layer with capital letters and symbols instead of numbers, etc. I just happen to have more layers like that :)
I use 2 extra thumb keys to switch between layers. I have a layer with numbers, symbols, and function keys, a layer with mouse movement, and a layer with macros. I can switch between them with a single key press.
The whole idea of the thumb cluster was very interesting for me. In standard keyboard thumb is used just for spacebar, which is waste of its potential. After all, evolving an opposable thumb allowed us to make tools and climb on top of the food chain. I can use it for 4 keys, and it's much more comfortable than stretching fingers to the top row.
I added there also home row mods
which means if I longpress a
I get cmd
, and longpress on d
gives me shift
, etc. This setup is mirrored on both sides, so I don't have to move my hands to use modifier keys.
The QMK fork for the Void keyboard linked in the repo works fine. There is a Vial browser editor or standalone app to change keybindings, and it's powerful. From normal keys, to mouse movement and macros. However, I wanted to add some additional options that were turned off by default for some reason. How hard can it be to compile some keyboard firmware, right?
Well...
The board I used, a cheap basic ProMicro 32U4, has VERY limited memory, so the original QMK firmware barely fits there. No more space for fireworks like tap dance. It reminded me of the conversation I had with a colleague at the smart home system company, where he worked as embedded software engineer. He was jealous of us mobile engineers discussing best practises, code readability etc. while they had to write hacks on hacks to make compiled code fit on the energy efficient chips. Now I get your struggle a bit better man.
But I was able to add home row mods and change some timeouts to make them feel better. After fighting with config files written in C, installing QMK with homebrew, learning that it's broken, fixing some dependencies manually because I use Apple Silicone, and talking with Claude to guide me through compilation, I made it.
I had my own firmware.
The wrong, pure QMK one, without Vial GUI. Vial QMK is a separate repo with a different configuration and setup.
I fixed that eventually, works as expected.
I got new keycaps. I wanted an XDA profile, primarily white. I had to put symbols with a Sharpie from other layers on them. The XDA profile means all keys are the same shape, no matter the row, which is useful for this build, since I may not put letters but symbols representing values from other layers.
This is just another variable to think about when building a keyboard.
Given how much time, materials, and profanity language I used while working on the keyboard, I'd be better off buying a basic assembled Corne keyboard.
But I had a lot of fun, learned a ton, and discovered a whole new world of my most commonly used computer peripheral.
And I want to play more with it. I want to make a concave shape keyboard like Dactyl, use hot swappable sockets, make a low profile wireless keyboard running on ZMK firmware, check tinting options for individual keys, or even 3d print a set of custom keycaps. I want to use Choc switches and PCB instead of hand-wiring and learn to design my own board from scratch.
The community around custom keyboards will be a fantastic inspiration for all that.
As I type this, a few packages from Aliexpress are heading to me and are full of parts I need for future keyboard projects. And they are wife-approved :)
2025-03-19 23:37:34
So, I have been mainlining Fedora Workstation for a couple of years now. My latest setup (which I bought before moving to Portugal!) is the Beelink SER6 PRO, currently running Fedora 41 at the time of writing.
It was initially a bit too fussy for me to mess around with, so I started off with Ubuntu on it (with Regolith). But the more I used Ubuntu, the more I felt disenfranchised with it as a personal computing distro. Fedora, while not perfect, is stable, modern, and the closest thing to what I want in a Linux desktop.
I’ve been using Linux for 15 years now. Started off just before I turned 18 with an old 17-inch HP laptop that could barely run alpha builds of Minecraft without crashing. I got tired of it, wiped Windows, and installed Ubuntu 10.04 LTS (Lucid Lynx). That was my entry point. Since then, I’ve gone through the usual distro-hopping phase, but Fedora has been my home for personal use for a while now.
Here's a quick look at my current setup:
I might write an article about the Moonlander MK I soon enough.
But no distro is perfect.
And I’m not sure why it has decided to act up as of late, but today it did—and it’s the second time it has.
This morning, I sat down to get some work done, and two very important things didn’t work:
These weren’t minor annoyances. These were core components of my workflow. Here’s what happened and how I fixed them.
The Bluetooth service was running, but my adapter wasn’t detected in bluetoothctl
. Running:
dmesg | grep -i bluetooth
revealed this:
Bluetooth: hci0: command 0xfc05 tx timeout
Bluetooth: hci0: Reading Intel version command failed (-110)
This error suggests that the Intel AX200 Bluetooth firmware failed to load, which is a known issue with some kernel versions and Intel chipsets. The system loads the driver (btusb
), but something in the initialization process fails.
This can be caused by:
btusb
kernel module, requiring a reload.
The easiest way to resolve this issue was to manually reload the btusb
module and restart the Bluetooth service:
sudo modprobe -r btusb
sudo modprobe btusb
sudo systemctl restart bluetooth
Immediately after running these commands, bluetoothctl list
showed my adapter again.
Since this happened twice, I didn’t want to manually fix it every time my system booted. The best way to automate the fix was by setting up a systemd service to reload the module at startup.
1️⃣ Create a systemd service file:
sudo nano /etc/systemd/system/bluetooth-fix.service
2️⃣ Add the following content:
[Unit]
Description=Fix Intel AX200 Bluetooth on Boot
After=bluetooth.service
Wants=bluetooth.service
[Service]
Type=oneshot
ExecStart=/usr/sbin/modprobe -r btusb
ExecStart=/usr/sbin/modprobe btusb
ExecStart=/bin/systemctl restart bluetooth
[Install]
WantedBy=multi-user.target
3️⃣ Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable bluetooth-fix.service
sudo reboot
After this, Bluetooth started working on boot without any manual intervention.
When I tried to launch Google Chrome, I got this error:
The profile appears to be in use by another Google Chrome process on another computer.
Chrome has locked the profile so that it doesn’t get corrupted.
This happens when Chrome doesn’t shut down properly and leaves behind a profile lock file. It thinks another process is using it, but there’s actually nothing running.
The likely causes:
First, I killed any lingering Chrome processes:
pkill -9 chrome
pkill -9 google-chrome
Then, I removed the lock files manually:
rm -rf ~/.config/google-chrome/SingletonLock
rm -rf ~/.config/google-chrome/Singleton*
After that, Chrome opened normally.
Fedora is a solid distro, but like any system, it has its quirks. The Bluetooth issue was a firmware-related bug that required a systemd fix, while the Chrome issue was a profile lock left over from a previous session.
Both problems had simple enough solutions, but if they’re happening to you, hopefully, this guide saves you some time.
2025-03-19 23:24:32
The world of open source licensing is ever-evolving, and today we take a closer look at the OpenLDAP Public License 2.8—a license that balances openness with legal clarity and fair compensation for developers. In our detailed exploration, we review its historical origins, strengths, challenges, and its role among other open source frameworks. For a comprehensive take, be sure to check out the original article, Unveiling OpenLDAP Public License 2.8: A Comprehensive Summary, Exploration and Review.
The OpenLDAP Public License 2.8 was developed to address a critical need in the open source community. It provides legal guidance for free projects while ensuring that the creative efforts of developers are protected. Born from decades of experience with similar licensing models, this license is designed not only to secure rights for contributors but also to promote an ecosystem where fairness is paramount. With its roots deeply embedded in legal robustness and community trust, the license has attracted discussions across various forums—from Hacker News to Stack Overflow.
This license stands in contrast to more permissive models like the MIT License, offering instead a more curated experience for developers who want both openness and protection. By addressing concerns over exploitation and misappropriation, the OpenLDAP Public License 2.8 represents a significant milestone in how we balance the ideals of open source with the practical necessities of legal safeguards.
At its core, the OpenLDAP Public License 2.8 is about providing a secure framework for open source projects. It is designed with a dual purpose in mind: maintaining high legal standards and ensuring that contributions are recognized and rewarded fairly. This focus on fairness is what truly sets the license apart amidst numerous alternatives available to developers today.
Developed by a community of experts and seasoned developers, the license has evolved over time, adapting to changing norms and technological advancements. Extensive discussions and revisions have molded it into a tool that many projects rely on to avoid ambiguous legal interpretations. Its robust framework, compared with licenses from well-known entities like OSI Licenses, demonstrates a commitment to clarity and sustainability. This stability has encouraged adoption by enterprise applications, directory services platforms, and middleware solutions that require dependable legal backing.
However, no licensing model is without its challenges. Critics have raised concerns about certain restrictive clauses that might hinder flexibility or cause issues when mixing with other license types. These challenges, often debated on platforms like Hacker News and Stack Overflow, emphasize the delicate balance between safeguarding developers’ rights and allowing commercial innovation. Despite these concerns, the OpenLDAP Public License 2.8 endures as a robust option for those seeking to navigate the intricate world of open source funding and fair code distribution.
An important aspect of this license is its advocacy for dual licensing and community-based funding models. While dual licensing offers versatility, it also raises legal complexities that require careful analysis. Some projects have successfully navigated these challenges by ensuring that their licensing framework adapts to multiple needs without compromising the core principle of fairness. This innovative approach is further exemplified by comparisons with blockchain-based compensation models—though the traditional legal structure remains central to the OpenLDAP framework.
In conclusion, the OpenLDAP Public License 2.8 is more than just a legal document—it is a testament to the evolving nature of software development and community collaboration. Its balanced approach, rooted in legal robustness and fair compensation, has made it indispensable to many open source projects. The license's historical evolution, comprehensive community support, and clear legal provisions continue to empower developers worldwide.
For anyone invested in understanding the interplay between open source licensing and fair code initiatives, exploring the nuances of tools like the OpenLDAP Public License 2.8 is essential. The detailed breakdown provided in the original article offers a deep dive into its implications that every project lead or developer should consider. Whether you are evaluating license options for your next project or simply exploring the rich history of open source legal frameworks, the journey through the OpenLDAP Public License provides valuable insights into balancing innovation with fairness.
For additional insights and resources, visit License Token and explore more discussions on OSI Licenses. Happy coding, and may your next project be both legally sound and creatively inspired!
2025-03-19 23:22:14
I've been working with React JS for several years now, and one topic that often comes up is using JWT tokens for authentication and secure communication.
This guide is my way of sharing a friendly walkthrough on how to use JWT tokens in React JS.
I want to explain why these tokens matter, how to set them up, and how you can overcome some common challenges along the way.
The goal is to make the concept clear, provide useful tips, and offer helpful resources that I have found valuable.
JWT, or JSON Web Token, is a compact and secure way to transmit information between parties as a JSON object.
It’s become very popular because it helps build secure applications. For example, many modern web applications use JWT tokens to manage user sessions without having to rely on server-side sessions.
This is especially useful in single-page applications like those built with React JS, where a fast, responsive user experience is key.
A survey by Auth0 showed that JWT is used in over 50% of web applications that require a token-based authentication system.
With such widespread use, understanding how JWT works and how to implement it in React is important for any developer who wants to build reliable and secure applications.
JWT tokens are structured in three parts: a header, a payload, and a signature. The header usually consists of the type of token and the algorithm used.
The payload contains the claims or information about an entity (like a user) and additional data. Finally, the signature ensures that the token hasn’t been tampered with.
Because JWT tokens are self-contained, they are very effective for authentication in distributed systems.
This means that once a user logs in, the server can generate a token and send it back to the client.
The client, built with React JS, stores this token—often in memory or local storage—and includes it in subsequent API calls.
This way, the server can verify the token and confirm the user's identity without needing to consult a database for every request.
Before diving into the code, it’s important to ensure that your development environment is ready. You’ll need Node.js installed, along with a package manager like npm or yarn. You can start a new React project using Create React App with a simple command like:
npx create-react-app my-jwt-app
This tool sets up everything you need to get started with a clean and modern React project. Once your project is up and running, you can begin installing libraries that help with managing JWT tokens.
For example, many developers choose to use Axios for HTTP requests because it’s simple to use and easy to integrate with token-based authentication.
Let me share a straightforward method to implement JWT authentication in your React project. The process generally involves:
User Login: Create a login form that collects the user’s credentials. When the user submits this form, send their credentials to the authentication server.
Receiving the Token: If the credentials are valid, the server responds with a JWT token. This token contains the information needed to verify the user's identity.
Storing the Token: For simplicity, you can store the token in local storage. However, be aware that local storage can be vulnerable to XSS attacks. In some cases, storing the token in memory or an HTTP-only cookie might be a safer choice.
Using the Token: When making API calls that require authentication, include the token in the Authorization header. This way, your backend can verify the token and allow access to protected resources.
Here’s a simplified version of how you might set up an Axios instance to include the JWT token:
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://your-api-domain.com',
});
apiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('jwtToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, (error) => Promise.reject(error));
export default apiClient;
In this snippet, every API request made using apiClient
will automatically include the token if it exists.
This approach simplifies the authentication process and reduces the amount of repeated code in your components.
Tokens are not meant to last forever. JWT tokens typically include an expiration time.
When a token expires, the user must re-authenticate, or you can use a refresh token mechanism if your system supports it.
It’s important to set up logic in your application to detect when a token has expired and to prompt the user to log in again.
For instance, you can use Axios interceptors to catch 401 Unauthorized responses and handle them accordingly.
While working with JWT tokens, I have noticed a few common challenges that many developers face:
Remember, the goal is to create an experience that is seamless for the user, while keeping their data safe and secure.
What is a JWT token?
A JWT token is a compact, URL-safe means of representing claims to be transferred between two parties. It is widely used for user authentication and secure data exchange.
How do I store a JWT token in a React application?
You can store a JWT token in local storage, but be mindful of potential security issues. Alternatives include storing it in memory or in HTTP-only cookies for increased security.
What happens if my JWT token expires?
If a token expires, your app should either prompt the user to log in again or use a refresh token (if implemented) to obtain a new token. Handling token expiration properly is crucial to maintaining a secure session.
Can I use libraries to help manage JWT tokens in React?
Yes, libraries like Axios for HTTP requests and state management tools such as Redux or Context API can make it easier to handle JWT tokens in your React application.
I have found several resources to be very useful for deepening your understanding of JWT tokens and React JS:
These resources have helped me refine my skills and understand the nuances of secure token management in web applications.
Working with JWT tokens in a React JS application can seem intimidating at first, but once you break down the steps, it becomes much more manageable.
I hope this guide has given you a clear overview of the topic and provided you with practical tips that you can implement in your own projects.
The examples and suggestions here are based on my own experiences and the trusted resources mentioned above.
I invite you to think about your own projects: What challenges have you faced with token-based authentication, and how did you overcome them? With the growing importance of secure user sessions and efficient authentication, I’d love to hear your thoughts and experiences on how to use JWT tokens in React JS.