Avoid plugging in the React ecosystem: a practical guide (2023)

Avoid plugging in the React ecosystem: a practical guide (1)

Three ways to avoid plugging in React: By usinguse context,component assembly, IStateLibrary for Advanced Public Administration.

Avoid plugging in the React ecosystem: a practical guide (2)

(Video) Why React.js is taking a new direction

·

to follow

--

(Video) 7 better ways to create a React app

In the React ecosystem, it is common to split an application into multiple components to make it more modular and reusable. As the component hierarchy increases, there is the challenge of passing data and state between components that are not directly nested, known as "plugging". This can lead to performance issues, code complexity, and maintainability issues.

In this article, we'll discuss three effective ways to avoid plugging in React: using the sameuse context,component assembly, IStateLibrary for Advanced Public Administration.

To demonstrate these techniques, we'll use the example of a user logging into the system on the login page with their saved credentialsRegisterState. This data should only be processed by the profile component embedded in the panel page.

// Login page.jsx
import { useState } as "react";
uvoz PainelPage iz './PainelPage'
export standard function LoginPage() {
const [login, setLogin] = useState({username: 'admin123', password: '12345'});


return (
<>


);
}
// PainelPage.jsx
Import ProfilePage from './ProfilePage'
export standard function PanelPage(props) {


return (
<>


);
}
// Profile page.jsx
export standard function ProfilePage(props) {
return (


Welcome {props.login.username}



)
}

In the accompanying code sample, we can observe the use of props to transfer credentials from one component to another. However, when a component needs to access state without being a direct parent component, inclusion occurs, in which data is passed through multiple intermediate components that do not use it directly. This leads to unnecessary rendering and reduces the reusability of the component.

use contextis a built-in React feature for sharing data between components without having to manually pass props at each level of the hierarchy. This is especially useful when you need to transfer common data across multiple components that don't change often.

Useuse contextFirst, let's create a context that stores the login status and allows access to it anywhere in the application. We can do this in the following way:

// LoginContext.jsx
importer { createContext, useState } von 'react';
eksport const LoginContext = createContext();
export const LoginProvider = ({children }) => {
const [prijava, setLogin] = useState();
return (

{Kinder}

);
};

In the code above, we create a context calledApplication contextmyth Reactscreate context()Function. Then we define the provider (Application service provider), which wraps child components (kinder). The provider provides a context value that contains the login status and a setLogin function to update.

To use this context in the application, we need to wrap the root componentApplication service provider:

// App.jsx
Uvezi Reager iz "reactor";
import { LoginProvider } from './LoginContext';
const App = () => {
// …
return (

{/* Rest of your application */}

);
};
export the given application;

💡When you need to recycleApplication service providerTo integrate a component into multiple projects, you can do so using an open source toolchain, e.gbit. Bit makes it easy to share, discover, and reuse individual components across multiple projectsmalo import your.username/LoginProviderTeams.

(Video) $6000 FFB PEDALS! - Gamechanger or Gimmick? | Simucube ActivePedal FULL REVIEW

Learn more here:

Now the login context is available for each component in theApplication service provider. We can access the context usinguse contextConnect components that require login state.

// Login page.jsx
importer { useState, useContext } von 'react';
importer { LoginContext } fra './LoginContext';
export standard function LoginPage() {
const [Benutzername, setUsername] = useState("");
const [Lozinka, setPassword] = useState("");
const { setLogin } = useContext(LoginContext);
// Rest of your code...
return (
<>

onSubmit={(e) => {
e.preventDefault();
setLogin({ username, password });
}}
>
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
value={password}
onChange={(e) => setPassword(e.target.value)}
/>




);
}

andlogin pagecomponents that we importApplication contextand useuse contextaccess hooksetLoginContext-based function. When the user submits the registration form, we update the registration status with a callsetLogin({ username, password }).

Correspondence inProfileA component that needs to access the login method we can useuse contextTo use credentials:

// Profile.jsx
importer { useContext } von 'react';
importer { LoginContext } fra './LoginContext';
export standard function Profile() {
const { login } = useContext(LoginContext);
// …
return (

Welcome, {login.username}!



);
}

Through exploitationuse contextWe eliminate the need to drill dowels and get direct access to the login methodProfileComponents.

Assembling components is another approach to avoid drilling dowels. Instead of directly passing props from one component to another, components are nested hierarchically to form a logical composition.

We can use the composition of components as follows:

// Login page.jsx
import { useState } aus 'reacted';
importer PanelPage fra './PanelPage';
Import ProfilePage iz './ProfilePage';
export standard function LoginPage() {
const [login, setLogin] = useState({ username: 'admin123', password: '12345' });
// …
return (



);
}

In the example above, ilogin pagea component whichprofile pagethe component is embeddedPanelPagecomponent as a child component. Thereforeprofile pageThe component receives the login properties directly as support.

// PanelPage.jsx
export standard function PanelPage({children}) {
return (

{Kinder}

);
}

andPanelPagecomponent, we use a special onekinderprop to display the content passed as a child. On this wayprofile pageThe component is displayed in itPanelPage.

// Profile page.jsx
Standard function ProfilePage({ login }) export {

// …
return (


Welcome {login.username}



);
}

andprofile pagethe component from which we get the login properties directlyRegisterand use them as usual to display the information you want.

In this way, the login properties are inherited directly fromlogin pagecomponent forprofile pageComponent by component composition.

Along with the above approaches, another way to avoid plug drilling in React is to use the state library. State is a lightweight state manager that provides an easy way to share and update state between components.

State allows you to create a global store that stores state and grants access to that state to components that need it. Components can subscribe to receive automatic updates on status changes, eliminating the need to manually send props.

(Video) From Junior To Senior React Developer - Best Practices

// store.js
Create an import from "Status";
const useStore = create((set) => ({
Register: {},
setLogin: (newLogin) => set(() => ({ login: newLogin })),
}));
Izvezi zadani UseStore;

💡Again, you can usebit to publish, version and reuse thisuseStoreConnect all your projects with one simplemalo import your.username/use-StoreTeams.

Find out more:

In the example above, we are creating a store withCabinetfunction from the state. The store has oneRegisterThe property that represents the initial state and asetLoginA function that allows updating the status.

To use the login method in the component, we can do the following:

// Login page.jsx
import { useState } aus 'reacted';
import useStore iz './store';
export standard function LoginPage() {
const [Benutzername, setUsername] = useState('');
const [Password, setPassword] = useState('');
const setLogin = useStore((state) => state.setLogin);
// …
return (
<>

onSubmit={(e) => {
e.preventDefault();
setLogin({ username, password });
}}
>
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
value={password}
onChange={(e) => setPassword(e.target.value)}
/>




);
}

we useuseStorereach hooksetLoginItem from state store. As soon as you submit the registration form, we will call yousetLoginUser name and password information feature.

Withinprofile pagecomponent, we can access the updated application status as follows:

// Profile page.jsx
import useStore iz './store';
export standard function ProfilePage() {
const login = useStore((state) => state.login);
// Rest of your code...
return (

Welcome {login.username}



);
}

On this wayprofile pageuser of the componentuseStorePlug in to automatically access the updated login mode from the state to avoid plugging.

Support drilling can be a challenge in React applications, but there are several methods to avoid it. In this article, we explored three ways to avoid dowel drilling: By using themuse context,component assembly, IStateLibrary.

Useuse contextit is possible to create a context to exchange data between components without having to manually pass props at each level of the hierarchy.component assemblyenables the hierarchical organization of the logical structure of components, eliminating the need to bring unnecessary props.Stateis a lightweight library that provides an easy way to share and update state between components.

Each approach has its advantages and it is important to consider the specifics of the project when choosing the most appropriate approach. By applying these techniques, it is possible to improve the performance, reusability and maintainability of React code.

Avoid plugging in the React ecosystem: a practical guide (4)

bitis an open source toolHelping more than 250,000 developers build apps with components.

Turn any UI, feature or page into a single entityreusable component- and share it in your apps. It's easier to collaborate and create faster.

(Video) ReactJs Learning Guide

find out more

Break apps into components to simplify app development and enjoy the best experience for the workflows you want:

FAQs

How many days does it take to learn React? ›

It will take you between one and six months to become proficient with the fundamentals of React. How quickly you learn React depends on your prior software development experience and how much time you are willing to put into learning.

Why can't browsers read JSX? ›

Because JSX is not valid JavaScript, browsers can't read it directly; they do not know what to do with it, so we need a transpiler to translate it to React. createElement() calls.

Is Redux a heavy library? ›

It's lightweight at 2KB (including dependencies), so you don't have to worry about it making your application's asset size bigger. With Redux, the state of your application is kept in a store, and each component can access any state that it needs from this store.

Why avoid Redux? ›

The main problem we face when using Redux and similar state management libraries is treating it as a cache for our backend state. We fetch the data , add it to our store with reducer and action, and then re-fetch from time to time, hoping that we are up to date.

Can I master React in 3 months? ›

Having guided dozens of juniors starting with React, I can say it takes much more than 3 months to be advanced for most people. Of course, some people might be faster. But being above average, as in, being better than 50% of all React devs, in 3 months is a bit of a stretch.

Can I learn react JS in 2 weeks? ›

ReactJS Basics

If you are a beginner or already have some programming experience, it will take you one to four weeks to completely master the basics.

Does Chrome understand JSX? ›

No, browsers can't understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand.

Why JSX is better than HTML? ›

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications.

Is JSX better than HTML? ›

One of the major differences between HTML and JSX is that in JSX, you must return a single parent element, or it won't compile. A lot of devs use <div>... </div> , but a better one that many people use is “fragment”, <>... </> which makes the code more readable.

Is Redux still relevant 2023? ›

Redux is no longer required to learn like it was in years past. The first reason for this is the release of the React Context API. In many cases, React developers used Redux to just pass data around their application's components. This is a job that React Context can do for us.

Is Redux no longer needed? ›

Now fast forward several years, the React ecosystem has grown so much, and the question arises, do we still need Redux? The answer for most cases is: No! You don't have to go to Redux as the default way to manage your React application's state anymore, and there are other alternatives that you can consider instead.

What are disadvantages of Redux? ›

Cons of Redux:
  • Overhead and complexity: Redux can add a significant amount of overhead and complexity to a project, especially for small or simple applications.
  • Steep learning curve: Redux can be difficult to learn, especially for developers who are new to state management and functional programming concepts.
Feb 10, 2023

What are easier alternatives to Redux? ›

Top Redux Alternatives to Consider for State Management in React
  • MobX.
  • Vuex.
  • Zustand.
  • GraphQL.
  • Jotai.
  • Recoil.
  • Rematch.
  • RxJS.
Jan 23, 2023

Should you put everything in Redux? ›

There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.

Why use Redux over hooks? ›

Redux can be used to assist you to manage the application data in projects of greater complexity, even though the new React Hooks additions useContext and useReducer allow you to control the global state. Both can be utilized if you're planning to construct an application.

Is it worth learning React in 2023? ›

Ten years later, it's natural to wonder: Should I learn React in 2023? The answer is yes, absolutely! React is still launching new features all the time and has the weight of Meta and their brilliant, dedicated engineering team behind it.

Can I learn React in 4 days? ›

For a programmer who is already familiar with HTML and at least one other programming language, learning React will take no more than a single day. React may be learned by a novice programmer in a matter of days. There are more libraries and technologies that may be used with React, such as Redux or Relay.

Why is React so hard to learn? ›

However, React is also difficult because it deals with advanced concepts like functional programming, compartmentalizing and passing state, using it with backend frameworks, and using it in conjunction with 3rd party software. If you want to learn React, the most important thing is to get started today and don't quit.

Is React more difficult than JS? ›

React JS is easier to grasp vs. JavaScript. Its well-defined lifecycle, component-based approach, and use of plain JavaScript make React JS very easy to learn. You can easily build and support mobile apps and professional websites.

Can I learn Reactjs in 10 days? ›

As with any skill, the more you practice, the better you get. React has a good learning curve in comparison to other web development frameworks, and so you should have no trouble learning the basics in a few days or weeks, and mastering the language in a few months.

How much JavaScript is enough to learn React? ›

Do I Need to Master JavaScript Before React? You do not need to master “all” JavaScript before moving to React. But, you need to have a solid grasp of the language. If you aim to become a web developer, you should understand Javascript, especially since it's the most popular programming language in this century.

What could be a disadvantage of React? ›

Cons
  • High Pace of Development. This is arguably the most discussed con of using React. ...
  • Flexibility and Lack of Conventions. Yes, you read it right. ...
  • Not a full-featured framework. ...
  • Poor Documentation. ...
  • JSX. ...
  • SEO Handling.
Nov 25, 2022

Is it better to use JS or JSX? ›

js from just the file name will help you as a developer a lot. EDIT: jsx is more than js, it is javascript + xml, which allows you to write html inside a js file without using template strings. For this reason it's a good practice to use . jsx for your react files, instead of .

What are the limitations of React? ›

5 Big Limitations of React
  • It's a Library, Not a Framework. Like other Javascript libraries, React contains pre-written code. ...
  • It Uses JSX. React uses JSX, a syntax extension to JavaScript. ...
  • Does Not Support SEO. React, by design, was not built with SEO in mind. ...
  • Lack of Updated Documentation. ...
  • Fast Development Speed.
Jan 7, 2023

What is the difference between Babel and JSX? ›

Babel : Babel is a JavaScript compiler that transform the latest JavaScript features, which are not understandable to every browser, into a backward compatible version of JavaScript in current and older browsers or environments. JSX : JSX is a syntactical extension to JavaScript.

Do I need Babel to use JSX? ›

With JSX, it is easy to define UI components in React. JSX should not be implemented directly by browsers, but instead requires a compiler to transform it into ECMAScript. This is where Babel comes in. Babel acts as this compiler allowing us to leverage all the benefits of JSX while building React components.

What is the difference between ES6 and JSX? ›

JSX stands for “JavaScript XML,” and it is a syntax extension to JavaScript based in ES6, the newest “version” of JavaScript. JSX allows you to write HTML in React by converting HTML into React components, helping you to more easily create user interfaces for your web applications.

What is the difference between XML and JSX? ›

The generated code runs faster than an equivalent code written directly in JavaScript. On the other hand, XML is detailed as "A simple, very flexible text format". A markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.

Is JSX and XML same? ›

JSX is an XML-like syntax extension to ECMAScript without any defined semantics. It's NOT intended to be implemented by engines or browsers. It's NOT a proposal to incorporate JSX into the ECMAScript spec itself.

What is the main difference between using JSX and JavaScript? ›

But first, let's settle what is the core difference between JavaScript and JSX. JavaScript is a programming language used for adding interactivity to web applications. On the other hand, JSX stands for JavaScript XML. It is a syntax extension for JavaScript that lets you use HTML tags right inside your JavaScript file.

Does NextJS replace Redux? ›

Instead of using Redux, Next. js uses data-fetching APIs that enable pre-rendering. These are great because your site becomes a set of static pieces that can be easily read by web crawlers, thus improving your site's SEO.

Can React replace Redux? ›

And yet, far too many React developers default to Redux for state management without considering other alternatives. In this tutorial, we'll introduce you to the React Context API for state management and explain how React Hooks and the Context API can replace Redux.

Do React hooks replace Redux? ›

Redux and React Hooks should be seen as complements and also as different things. While with the new React Hooks additions, useContext and useReducer, you can manage the global state, in projects with larger complexity you can rely on Redux to help you manage the application data.

Does Redux make app slow? ›

For simple apps, using Redux or MobX with a persistence adapter is the easiest way to go. But when you start scaling to thousands or tens of thousands of database records, your app will now be slow to launch (especially on slower Android devices).

Why use Redux over local storage? ›

Redux and localStorage have different use cases actually. Redux you'll use to manage your application state across multiple components. Local Storage you'll use to persist properties in the browser for later usage. The problem is that any change on your localStorage won't reflect on your application.

Why Redux Toolkit over Redux? ›

Why You Should Use Redux Toolkit​ Redux Toolkit makes it easier to write good Redux applications and speeds up development, by baking in our recommended best practices, providing good default behaviors, catching mistakes, and allowing you to write simpler code.

Is Redux maintained by Facebook? ›

Redux was created by Dan Abramov and is maintained by Facebook. Redux is an open-source JavaScript library that allows you to manage application state. It can be used in any programming language like React or Vue. Redux was created by Dan Abramov and is maintained by Facebook.

What are 3 main concepts of Redux? ›

Redux can be described in three fundamental principles:
  • Single source of truth​ The global state of your application is stored in an object tree within a single store. ...
  • State is read-only​ The only way to change the state is to emit an action, an object describing what happened. ...
  • Changes are made with pure functions​
Jun 25, 2021

Why Redux is better than context API? ›

Typically, we choose Redux for global state management if we work on a larger, complex project. If the project is smaller, or we focus on encapsulating modules, it is worth using the Context API. At Studio Software, we work with you in mobile and web application development.

What is the most popular Redux middleware? ›

Redux thunk is the most popular middleware that allows you to call action creators, which then returns a function instead of an action object.

Which is better Redux or hooks? ›

Redux and React Hooks should be viewed as both complementary and distinct concepts. Redux can be used to assist you manage the application data in projects of greater complexity, even though the new React Hooks additions useContext and useReducer allow you to control the global state.

Is Redux good for small projects? ›

Redux is most useful in cases when:

You have large amounts of application state that are needed in many places in the app. The app state is updated frequently. The logic to update that state may be complex. The app has a medium or large-sized codebase, and might be worked on by many people.

What is the difference between global state and local state in Redux? ›

What is the global state in react? Local state is sufficient when the data is shared within a single component. But when it comes to sharing data among multiple unrelated react components, we have to look for something beyond the local state. The global state is what we are looking to implement.

Can we have more than one store in Redux? ›

As with several other questions, it is possible to create multiple distinct Redux stores in a page, but the intended pattern is to have only a single store. Having a single store enables using the Redux DevTools, makes persisting and rehydrating data simpler, and simplifies the subscription logic.

What is the difference between Redux and context API? ›

Redux is an open-source library that creates and manages a global shared state which is referred to as a single source of truth. Actions and reducers are used to manipulate this store. React Context API is a state management solution that is built-in with react.

Is it better to use Hooks in React? ›

Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes. Below are code examples to illustrate React class and functional components.

Should you combine Hooks with Redux? ›

We recommend using the React-Redux hooks API as the default approach in your React components. The existing connect API still works and will continue to be supported, but the hooks API is simpler and works better with TypeScript.

Why Hooks are better than hoc? ›

HOC helps to isolate logic and state management in a separate class-based component. With React Hooks, state management can occur outside of a class. Hooks empower developers to use the functional programming aspects in React. There are standard hooks, and we can write custom hooks.

Can you learn React in 3 days? ›

For a programmer who is already familiar with HTML and at least one other programming language, learning React will take no more than a single day. React may be learned by a novice programmer in a matter of days. There are more libraries and technologies that may be used with React, such as Redux or Relay.

Can I learn ReactJS in 10 days? ›

As with any skill, the more you practice, the better you get. React has a good learning curve in comparison to other web development frameworks, and so you should have no trouble learning the basics in a few days or weeks, and mastering the language in a few months.

Is React very difficult to learn? ›

Thankfully, React is easy to learn, but only once you have foundational knowledge in JavaScript. Of course, the difficulty that comes with learning anything new is somewhat subjective. Regardless of your prior experience, plenty of resources are available to help make React easier to learn.

Can I learn react JS in 15 days? ›

I learnt React JS in 15 days. On my way, I had to learn JavaScript ES6 and Node JS. I also did a small project for practice. The conclusion I derived from these 15 days is that the fastest way to learn React JS is to practice it in a project.

Is learning React harder than JavaScript? ›

React is much harder to learn than JavaScript if you attempt to learn it first. This is because you will be essentially learning both languages at the same time. Mainly because a lot of React is actually pure vanilla JavaScript. However, if you try to learn JavaScript first, learning React will be incredibly easy.

Is React easy for beginners? ›

Small learning curve: React is easy to learn, as it mostly combines basic HTML and JavaScript concepts with some beneficial additions. Still, as is the case with other tools and frameworks, you have to spend some time to get a proper understanding of React's library.

Do React developers get paid well? ›

The highest recorded salaries for ReactJS developers in the US are around $144k/yr and the lowest around $59k/yr. Entry level salaries start from around $52k/yr and senior developers can expect salaries as high as $191k/yr.

Why is React hard? ›

However, React is also difficult because it deals with advanced concepts like functional programming, compartmentalizing and passing state, using it with backend frameworks, and using it in conjunction with 3rd party software. If you want to learn React, the most important thing is to get started today and don't quit.

Is React easier than Python? ›

Python is easy to learn while ReactJS can be difficult to learn if you don't have experience with JavaScript. Python has a large number of libraries and frameworks available while ReactJS has a smaller number. Python code is typically shorter and easier to read than ReactJS code.

Is React harder than flutter? ›

Both frameworks have unique benefits and drawbacks that must be considered when determining. However, if we had to choose one, we would say Flutter is slightly easier to learn than React Native. Flutter uses Dart, a relatively easy language to learn, while React Native uses JavaScript, which can be a bit more tricky.

Can I learn React in 30 days? ›

Learn React by building Applications

It is structured based on days and the challenge goes form day 1 to 30. In the 30 Days Of React challenge , you will have a chance to practice with small exercises, solve different challenging problems and build more than 30 simple and complex applications.

What is the fastest way to learn ReactJS? ›

With that being said, let's go through the step-by-step process of learning React.
  1. Learn JavaScript first. ...
  2. Take a look at React's starter guide. ...
  3. Watch some tutorial videos. ...
  4. Build some React JS projects. ...
  5. Use the React documentation as the reference. ...
  6. Read React blog posts and articles. ...
  7. Join an online React community.
Dec 8, 2022

Is React better than Angular? ›

In terms of performance, bundle size, and backward compatibility, React outperforms Angular. The component-driven architecture of React allows developers to reuse code components, which tends to save cost and time. It also outperforms Angular due to its rendering optimizations and Virtual DOM implementation.

Should I learn Nextjs after React? ›

Many developers find that learning React first is a good place to start before diving into learning next. js. React is a JavaScript library for building user interfaces, and it lets you create reusable components so that your code is easy to read and maintain.

Videos

1. I survived 100 Days in a DESERTED WASTELAND in Minecraft and Here's What Happened
(Socksfor1)
2. This is the Only Right Way to Write React clean-code - SOLID
(CoderOne)
3. Why & When I Use React JS
(Dennis Ivy)
4. The aftermath of laying your PS5 on its side… #ps5 #playstation #playstation5 #gaming #games #gamer
(Out Of The Box)
5. The biggest ant
(Lights Camera Ants)
6. This is a Morphed Axolotl 🦎
(Aquarium Info)

References

Top Articles
Latest Posts
Article information

Author: Kelle Weber

Last Updated: 06/09/2023

Views: 6656

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Kelle Weber

Birthday: 2000-08-05

Address: 6796 Juan Square, Markfort, MN 58988

Phone: +8215934114615

Job: Hospitality Director

Hobby: tabletop games, Foreign language learning, Leather crafting, Horseback riding, Swimming, Knapping, Handball

Introduction: My name is Kelle Weber, I am a magnificent, enchanting, fair, joyous, light, determined, joyous person who loves writing and wants to share my knowledge and understanding with you.