Muskan Sheikh, Author at Perficient Blogs https://blogs.perficient.com/author/msheikh/ Expert Digital Insights Thu, 26 Dec 2024 08:26:28 +0000 en-US hourly 1 https://blogs.perficient.com/files/favicon-194x194-1-150x150.png Muskan Sheikh, Author at Perficient Blogs https://blogs.perficient.com/author/msheikh/ 32 32 30508587 State Persistence in Recoil using Local Storage https://blogs.perficient.com/2024/12/26/state-persistence-in-recoil-using-local-storage/ https://blogs.perficient.com/2024/12/26/state-persistence-in-recoil-using-local-storage/#respond Thu, 26 Dec 2024 08:20:02 +0000 https://blogs.perficient.com/?p=374433

Ever wish your app could remember things like a user’s theme choice, preferences, or other settings, even after a page reload? Good news: it absolutely can!

With Recoil, your trusty state management tool, and localStorage, the browser’s built-in memory, you can easily persist your app’s state. That means no more resetting the theme or losing data when users refresh or come back later.

And the best part? You don’t need anything complicated. just a few lines of code with Recoil and localStorage. It’s so easy, you’ll wonder why you didn’t do it sooner!

This small tweak makes your app seamless and user-friendly, like it has a memory that syncs with your users.

Ready to add persistence to your app with Recoil? Let’s get started!

First, check out my other blogs on Recoil to get a solid foundation. I cover basics like Recoil Intro Part and Recoil Hooks to help you get the most out of Recoil.

 

Main Advantages of Implementing State Persistence in Recoil with Local Storage –

Key benefits of persistence in recoil

Coding Example:

Let’s Implement the State Persistence in Recoil with Local Storage for Theme Preference

state.js –

import { atom } from 'recoil';

// Atom to store the mode (light or dark)
export const modeState = atom({
  key: 'modeState',  // Unique ID for the atom
  default: 'light',  
});

App.js-

import React, { useEffect } from 'react';
import { useRecoilState } from 'recoil';
import { modeState } from './state';

const App = () => {
  const [mode, setMode] = useRecoilState(modeState);

  // Load mode from localStorage
  useEffect(() => {
    const savedMode = localStorage.getItem('modeState');
    if (savedMode) {
      setMode(savedMode); // Set the mode if found in localStorage
    }
  }, [setMode]);

  // Save mode to localStorage whenever it changes
  useEffect(() => {
    localStorage.setItem('modeState', mode);
    document.body.className = mode; // Apply the mode to the body class
  }, [mode]);

  return (
    <div>
      <h1>Current Mode: {mode}</h1>
      <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>
        Change Mode
      </button>
    </div>
  );
};

export default App;

Index.js –

import React from 'react';
import ReactDOM from 'react-dom';
import { RecoilRoot } from 'recoil';
import './index.css';
import App from './App';

ReactDOM.render(
  <RecoilRoot>
    <App />
  </RecoilRoot>,
  document.getElementById('root')
);

index.css-

/* Default light mode */
body.light {
  background-color: white;
  color: black;
}

/* Dark mode */
body.dark {
  background-color: #121212;
  color: white;
}

button {
  padding: 10px 20px;
  cursor: pointer;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
}

button:hover {
  background-color: #0056b3;
}

Explanation:

This app saves and loads the theme from localStorage, and the mode can be toggled between light and dark.

  1. State Management: The modeState atom in Recoil stores the current mode (light or dark).
  2. Persistence: On page load, the app checks localStorage for the saved mode. If found, it applies the saved mode. When the mode changes, it is saved back to localStorage.
  3. Mode Toggle: A button toggles between light and dark modes, updating the background color and saving the mode to localStorage.
  4. Page Refresh: The selected mode persists across page refreshes, maintaining the last chosen theme.

 

Output:

 

Output

  1. When the app loads, it checks localStorage for a saved mode (light or dark) and uses it. If no mode is found, it defaults to light mode.
  2. Clicking the “Change Mode” button switches between light and dark modes and changes the background color.
  3. The app saves the selected mode to localStorage whenever it changes.
  4. When you refresh the page, the app gets the saved mode from localStorage and uses it, keeping the same mode.

 

In Inspect Mode (Developer Tools), go to the Application tab to see localStorage entries where the light/dark mode is saved. When the mode is toggled, the localStorage value updates with the new mode. After refreshing the page, the saved mode is retrieved from localStorage and applied, which you can verify by checking both localStorage and the body class in the Elements tab.

Inspect mode persistence

In short, using Recoil with localStorage saves user settings like the theme here between sessions and page reloads, making the experience more consistent and personalized.

Conclusion:

Using Recoil with localStorage is a win-win for both users and developers. For users, it means their preferences, like the theme, are saved across sessions, making the experience feel seamless and personalized every time they return. For developers, it takes the hassle out of managing state persistence. With Recoil handling the app’s state and localStorage automatically saving settings, developers can focus on building excellent features instead of worrying about saving and loading data. This combination makes the development process smoother, faster, and more efficient.

That’s a wrap for today! But don’t go too far. I’ll be diving into tools and techniques that make development easier and more exciting. Until then, keep experimenting, stay curious, and happy coding!

]]>
https://blogs.perficient.com/2024/12/26/state-persistence-in-recoil-using-local-storage/feed/ 0 374433
Unlocking the Potential of Recoil: Essential Recoil Hooks Every React Developer Should Know https://blogs.perficient.com/2024/12/24/unlocking-the-potential-of-recoil-hooks/ https://blogs.perficient.com/2024/12/24/unlocking-the-potential-of-recoil-hooks/#comments Tue, 24 Dec 2024 18:23:51 +0000 https://blogs.perficient.com/?p=374418

If you are enjoying using React but find managing state tricky, you need to know about Recoil hooks. They’re made for React developers who want a simpler, more powerful way to handle the state. Let’s jump in and see how it works!

First, we will look at what hooks are in React and their basic definition –

In React, hooks are like unlocking secret abilities for your functional components. They let you add state, perform side effects, and control your app’s lifecycle, all while keeping your code neat and easy to manage and with no classes required!

In my previous blog, we introduced Recoil, covering atoms and selectors and how to create them. Consider this blog as part 2 of the Recoil blog. In this blog, we’ll look at Recoil hooks and see how they can make state management in React easier and more efficient.

Let’s see what the difference is between React hooks and Recoil hooks –

 

Recoil hook

Let’s explore Recoil hooks. These simple hooks manage global state with atoms and selectors, making state handling easy in larger apps. Here’s a quick list:

 

useRecoilState: This is similar to React’s useState; this hook returns both the current value of an atom and a function to update it. It’s ideal when you need to both read and modify the state.

useRecoilValue: This hook allows you to retrieve the current value of an atom or selector without modifying it. It’s perfect when you only need to read the state and don’t need to trigger updates.

useSetRecoilState: Instead of accessing both the current value and the update function, this hook provides only the function to modify an atom’s value directly. It’s great for situations where you only need to update the state.

useResetRecoilState: This hook resets the atom’s value to its default state, which is useful for clearing or resetting data within your app.

These hooks make it easy to manage state in Recoil, allowing you to read, update, or reset values based on what you need.

A Quick Differentiation of Recoil Hooks for Reading, Writing, or Updating State:

Recoilhook Checklist

Here’s an example to show how these hooks can be used in action –

Coding Example –

First, we need to create the Recoil atoms that represent global states, which the components will access and manipulate throughout the application.

import { atom } from 'recoil';

export const counterAtom = atom({
  key: 'counterAtom', // unique ID for the atom
  default: 0, // default value
});

This code creates a Recoil atom named counterAtom with a unique identifier (key) and an initial value of 0, allowing the counter’s state to be shared and updated across components using Recoil hooks.

useRecoilValue –

import React from 'react';
import { useRecoilValue } from 'recoil';
import { counterAtom } from '../src/atom';

const Counter = () => {
  const counter = useRecoilValue(counterAtom);

  return <div>Counter Value: {counter}</div>;
};

export default Counter;

The above code uses the useRecoilValue hook to read the current value of the counterAtom and display it. This hook provides read-only access to the atom’s state in the component.

useSetRecoilState:

import React from 'react';
import { useSetRecoilState } from 'recoil';
import { counterAtom } from '../src/atom';

const IncrementButton = () => {
  const setCounter = useSetRecoilState(counterAtom);

  return <button onClick={() => setCounter((prev) => prev + 10)}>Increment</button>;
};

export default IncrementButton;

Here, we are using the IncrementButton component, which utilizes useSetRecoilState to access a function (setCounter) that updates the counterAtom state. When clicked, the button adds 10 to the counter value using setCounter.

useRecoilState:

import React from 'react';
import { useRecoilState } from 'recoil';
import { counterAtom } from '../src/atom';

const CounterWithButtons = () => {
  const [counter, setCounter] = useRecoilState(counterAtom);

  return (
    <div>
      <div>Counter Value: {counter}</div>
      <button onClick={() => setCounter(counter + 10)}>Increment</button>
      <button onClick={() => setCounter(counter - 10)}>Decrement</button>
    </div>
  );
};

export default CounterWithButtons;

The CounterWithButtons component uses the useRecoilState hook to get and update the value of counterAtom. It provides the current value (counter) and a function (setCounter) to change the state.

useResetRecoilState:

import React from 'react';
import { useResetRecoilState } from 'recoil';
import { counterAtom } from '../src/atom';

const ResetButton = () => {
  const resetCounter = useResetRecoilState(counterAtom);

  return <button onClick={resetCounter}>Reset Counter</button>;
};

export default ResetButton;

The ResetButton component uses the useResetRecoilState hook to get a function (resetCounter) that resets counterAtom. When the button is clicked, it resets the counter to its initial value.

Conclusion:

Recoil makes managing state in React smooth and enjoyable! With hooks like useRecoilValue, useSetRecoilState, and others, it ensures your app’s state stays organized and easy to handle. It’s like having a smart teammate who manages the state while you focus on building the app’s features.

That’s all for today! But stay tuned for more posts on state management libraries that are coming your way to help you take your projects to the next level. Until then, keep experimenting, and happy coding!

]]>
https://blogs.perficient.com/2024/12/24/unlocking-the-potential-of-recoil-hooks/feed/ 1 374418
Redux vs Zustand: A Quick Comparison https://blogs.perficient.com/2024/12/18/redux-vs-zustand-a-quick-comparison/ https://blogs.perficient.com/2024/12/18/redux-vs-zustand-a-quick-comparison/#respond Wed, 18 Dec 2024 08:57:06 +0000 https://blogs.perficient.com/?p=373845

Imagine you’re in a library. Redux is like a huge, well-organized library where every book is perfectly categorized, labeled, and placed in its specific spot. It’s ideal for a massive collection, but getting everything in order can take a lot of time. Zustand, on the other hand, is like a comfy reading corner with just a few handpicked books. Everything is right at your fingertips, and you don’t have to spend time organizing it; pick up what you need and enjoy.

In this blog, we’ll explore Redux and Zustand to help you decide which is the perfect fit for your project, whether you’re managing a huge amount of state or just need a few key pieces.

In a previous blog, I explored the essential factors to keep in mind when picking a state management library. Now, let’s take a closer look at what makes Redux and Zustand stand out in this decision-making process.

Reduxvsxustand

Each library, whether it’s Redux or Zustand, has its own challenges. Let’s discuss the downsides!

Redux:

  • Challenging for Beginners: Mastering Redux can be tough for newcomers due to its complex concepts like reducers and middleware.
  • Code Bloat: Expect lots of boilerplate code, especially for simpler tasks, which can slow down the development process.
  • Too Complex for Small Apps: Redux can be over-engineered for smaller projects, adding unnecessary complexity and extra code.

Zustand:

  • Limited Middleware: No built-in tools for side effects like Redux, so you need to set it up yourself.
  • Smaller Community: Fewer resources and tutorials compared to Redux.
  • Not for Complex State: Not the best for very large or complex state management.

Implementing with Code

Let’s dive into some code examples to showcase how Redux and Zustand work in action.

Redux:

Install the packages of Redux by executing the command below:

npm install @reduxjs/toolkit react-redux

Example –

Let’s create a simple counter application using Redux for state management within a React application. Here’s how we can implement it step by step:

Action.js:

export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });

reducer.js

const counterReducer = (state = 0, action) => {
    switch (action.type) {
      case 'INCREMENT':
        return state + 1;
      case 'DECREMENT':
        return state - 1;
      default:
        return state;
    }
  };
  
  export default counterReducer;

Store.js

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './reducer';

// Create Redux store using configureStore
const store = configureStore({
  reducer: counterReducer
});

export default store;

App.js

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement } from './actions';

function App() {
  const count = useSelector((state) => state); // Access state from Redux store
  const dispatch = useDispatch();

  return (
    <div style={{ textAlign: 'center' }}>
      <h1>{count}</h1>
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store'; // Import the store

// Wrap your app with Provider and pass the Redux store
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Key Redux Concepts:

  • Centralized State: Redux stores the entire application state in a single, immutable store, providing a consistent state across the app.
  • Actions & Reducers: Actions are dispatched to signal state changes. Reducers respond by updating the state based on these actions in a pure, predictable manner.
  • Boilerplate Code: Redux often involves a significant amount of boilerplate, requiring explicit definitions for actions, reducers, and the store setup.
  • React Integration: The react-redux library is used to connect React components to the Redux store, enabling state access and updates via useSelector and useDispatch hooks or connect function.

Zustand:

To install Zustand –

npm install Zustand

 

Example –

Store.js

import { create } from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 }))
}));

export default useStore;


App.js

// App.js (React Component)
import React from 'react';
import useStore from './store';  // Import the Zustand store

function App() {
  // Accessing the state and actions from Zustand store
  const { count, increment, decrement } = useStore();

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default App;

index.js

// index.js (React entry point)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';  // Import the App component

// Rendering the App component into the DOM
ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Key Zustand Concepts:

  • Minimal Setup: Create a store with a single create() function.
  • Direct State Manipulation: State is mutated directly in the store, without actions or reducers.
  • No Boilerplate: Simple, intuitive API with minimal setup.
  • React Integration: Use the useStore hook to access state and actions in components.

 Choosing between Redux and Zustand –

Picking between Redux and Zustand is like choosing between a powerful engine and a smooth ride. Redux offers a ton of features, making it perfect for big, complex applications, but it requires time and effort to learn. Zustand, on the other hand, is the go-to for quick, simple projects, giving you fast setup and ease of use with minimal fuss. Need power and customization? Redux is your choice. Want speed and simplicity? Go with Zustand. Whether you need to build something scalable or just get the job done fast.

In my opinion, the key is understanding your project’s needs. Once you do, you can choose the right tool for smooth development and easy state management.

Pick wisely according to what aligns best with your workflow! That’s it for today, but don’t worry; more posts on state management libraries are coming soon to help you level up your projects. Until then, keep experimenting, and happy coding!

]]>
https://blogs.perficient.com/2024/12/18/redux-vs-zustand-a-quick-comparison/feed/ 0 373845
State Management in React with MobX https://blogs.perficient.com/2024/12/17/state-management-in-react-with-mobx/ https://blogs.perficient.com/2024/12/17/state-management-in-react-with-mobx/#respond Tue, 17 Dec 2024 14:20:53 +0000 https://blogs.perficient.com/?p=373744

Imagine a world where state management is as simple as it should be. MobX lets you build reactive UIs with zero fuss. Using reactive programming, MobX automatically keeps your UI in sync with your app’s state. There is no need for the boilerplate chaos of actions and reducers. With just a few lines of code, you can make your state observable, and MobX will handle the rest, updating the UI whenever the state changes.

Introduction to MobX – 

As mentioned in my last blog, MobX is an excellent tool for React developers to manage dynamic data easily. It works behind the scenes, automatically updating the user interface whenever the data changes, so you don’t need to manually handle updates. This makes state management in your app much cleaner and more scalable, especially when dealing with frequently changing data.

MobX is a state management library that ensures your app’s data and UI are always in sync by observing specific parts of your data. Think of it as a helper that watches your app’s data and keeps the UI updated whenever something changes. While it works seamlessly with React, MobX can also be used with other JavaScript frameworks or even in plain JavaScript.

React and MobX

Setting Up MobX in Your React Application 

To get started, the first step is to install MobX in your project:

npm install mobx mobx-react

 

Look at the package.json file, MobX has been installed in our project.

MobX package

Let’s cover the core concepts of MobX with an example—

Key points of MobX

 

Let’s take an example to see how we use MobX to manage the state in our React app.

 

App.js –

import React from 'react';
import { observer } from 'mobx-react-lite';
import store from './store'; 

const ComponentA = observer(() => {
  return (
    <div>
      <ComponentB />
    </div>
  );
});

const ComponentB = observer(() => {
  return <ComponentC />;
});

const ComponentC = observer(() => {
  return (
    <div>
      <p>{store.data}</p>
      <button onClick={() => store.updateData("Updated the data from Component C")}>
        Update Data
      </button>
    </div>
  );
});

export default ComponentA; 

Component A: Root component. No need to pass data through props

Component B: Directly render Component C (no prop drilling)

Component C: Will directly access the data from the store

Store.js –

import { makeAutoObservable } from 'mobx';

const store = makeAutoObservable({
  data: "Welcome to MobX Store",

  updateData(newData) {
    this.data = newData;
  }
});

export default store; 

Here we are creating a MobX store with an observable data property.

and an updateData action to modify it using makeAutoObservable.

Now just create a root and render the ComponentA to the DOM using ReactDOM. createRoot in index.js.

Let’s sum it up. MobX is used to manage the state with an observable store. The data is made observable in the store, and any component wrapped with the observer function automatically updates when the state changes. The updateData function is an action that modifies the data in the store. When the action is triggered, components that observe the store reactively update and reflect the new data. This setup avoids prop drilling, as components directly access the store, making state management efficient and ensuring the UI stays in sync with the data changes.

Let’s discuss some of the benefits of choosing MobX:

Benefits of MobX

 

Like any other tool, MobX comes with some limitations.

Let’s discuss—

Limitations of MobX

FAQs about MobX

  • What is the difference between npm install –save mobx and npm install mobx mobx-react? npm install –save mobx installs only MobX, while npm install mobx mobx-react installs both MobX and mobx-react, which is required for integrating MobX with React.

 

  • Is MobX suitable for use in non-React applications? Yes, MobX is compatible with non-React applications. It is a versatile state management library that can be used with or without any JavaScript framework.

 

  • Is MobX still relevant in 2025? Yes, MobX is still relevant in 2025. While other tools like Redux Toolkit and Zustand have gained popularity, MobX remains a solid choice for state management due to its features.

Conclusion –

In short, MobX makes state management easy by keeping your app’s data and UI in sync, so you can focus on building features. It only updates the parts of the UI that need it, making things faster and more efficient. With a simple API and automatic updates, MobX helps you create responsive apps without the hassle of managing the state.

That’s it for today! But stay tuned. I’ll be exploring more state management libraries in future posts and showing how they can improve your projects. Until then, keep experimenting, and happy coding!

]]>
https://blogs.perficient.com/2024/12/17/state-management-in-react-with-mobx/feed/ 0 373744
State Management in React with Recoil https://blogs.perficient.com/2024/11/29/state-management-in-react-with-recoil/ https://blogs.perficient.com/2024/11/29/state-management-in-react-with-recoil/#respond Fri, 29 Nov 2024 13:17:06 +0000 https://blogs.perficient.com/?p=372655

Have you ever created a React application and ended up struggling with tangled state updates, excessive prop drilling, or overly complex context setups? You’re definitely not alone! As your app scales, managing the state in React can become quite tricky. This is where Recoil comes to the rescue, a powerful new library designed to streamline state management in a way that feels almost like magic. 

Don’t worry, though; you don’t need to be a React pro to grasp it. In this blog, we’ll explore what Recoil is and why it could be the perfect solution to help you maintain a clean, efficient, and easy-to-manage app. 

In my previous post, I began a detailed exploration of “State Handling Excellence in React,” where we discussed some of the most widely used state management libraries in the React ecosystem. 

Introduction to Recoil – 

In my previous blog, we explored Recoil, a state management library created by Facebook that offers a smooth solution for managing the state in React applications. It’s particularly effective for small to medium-sized projects, enhancing React’s built-in functionality with powerful tools that simplify complex tasks. Recoil allows developers to handle the state in a flexible way, tailored to the specific needs of their projects. 

In this post, we’ll dive into Recoil’s core features – atoms and selectors, which serve as the foundation for easy and efficient state management. 

Setting Up Recoil in Your React Application 

To get started, the first step is to install Recoil in your project: 

npm install recoil

 

Look at the package.json file, Recoil has been installed in our project. 

Package json

After setup, Recoil requires the RecoilRoot component at the top level of your app, like how Redux requires the Provider to wrap the application. 

Recoil – 

import { RecoilRoot } from 'recoil';                                                      
ReactDOM.render(
  <RecoilRoot>
    <App />
  </RecoilRoot>,
  document.getElementById('root')
);

Redux – 

import { Provider } from 'react-redux';
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Diving Into the Core Concepts of Recoil – 

Atoms: 

  • Data Containers: Atoms act as mini storage units where you keep your app’s data (like numbers, strings, or objects). 
  • Accessible Anywhere: Any component in your app can grab or change the contents of an atom, no matter where it is. 
  • Instant Updates: Whenever the value inside an atom changes, all components using that atom automatically refresh to reflect the new data. 
  • Skip the Prop Passing: Atoms let you avoid prop drilling, so you don’t have to pass data through multiple layers of components. 
  • Lightweight & Powerful: Atoms are quick to set up and make managing state across your app much easier and more efficient. 

Creating an Atom in Recoil – 

import { atom } from 'recoil';
export const nameState = atom({
  key: 'nameState',  
  default: 'Muskan',  
});

Here we are creating an atom named nameState in Recoil. It uses the unique identifier ‘nameState’ and sets the default value to ‘Muskan.’ This atom holds data that can be accessed and modified across various components in your app. 

Now, let’s move on to another key concept: selectors. 

Selectors- 

  • Dynamic State Calculation: Selectors let you compute or transform data from atoms or other selectors, generating dynamic values. 
  • Auto Update: When an atom’s state changes, the selector automatically updates the derived value. 
  • Efficient Rendering: Selectors trigger re-renders only when their derived value changes, boosting app performance. 
  • No Extra Tracking: Forget about manual tracking – selectors automatically manage changes to dynamic data. 
  • Streamlined Logic: Use selectors to simplify complex state logic and keep your code more organized and maintainable. 

Creating a Selector in Recoil 

import { selector } from 'recoil';
import { nameState } from './state'; // Importing the atom that holds the name
export const nameLengthSelector = selector({
  key: 'nameLengthSelector',  
  get: ({ get }) => {
    const name = get(nameState); // Retrieving the value of nameState atom
    return name.length;  
  },
});

The nameLengthSelector is a selector that dynamically calculates the length of the string stored in the nameState atom. By utilizing the get function, it fetches the current value of the nameState and computes its length. This approach enables automatic calculation of the name’s length, eliminating the need for manual updates or redundant calculations throughout the app. 

In addition to atoms and selectors, Recoil provides several standout features: 

  • Efficient Re-renders: Only the components that use the changed state will re-render, improving app speed. 
  • Global and Local State: Recoil makes it easy to manage both global and local state in your app. 
  • No Prop Drilling: You don’t have to pass data through many layers of components, as atoms and selectors give components direct access to the state. 

These features make Recoil a simple and powerful choice for managing state in React apps. 

Conclusion – 

Recoil makes state management in React simple and efficient. It simplifies managing both global and local state, removes the need for prop drilling, and boosts performance by re-rendering only when necessary. With its easy-to-understand API and clear concepts like atoms and selectors, Recoil is an ideal choice for developers looking for a fast and straightforward way to manage state in React! 

That’s a wrap for today! But don’t go too far; I’ll be diving deeper into more state management libraries in future posts, uncovering how they can level up your projects. Until then, keep experimenting, and happy coding! 

]]>
https://blogs.perficient.com/2024/11/29/state-management-in-react-with-recoil/feed/ 0 372655
Introduction to State Handling Excellence in React- A Developer’s Perspective https://blogs.perficient.com/2024/11/14/introduction-to-state-handling-excellence-in-react-a-developers-perspective/ https://blogs.perficient.com/2024/11/14/introduction-to-state-handling-excellence-in-react-a-developers-perspective/#comments Thu, 14 Nov 2024 12:46:46 +0000 https://blogs.perficient.com/?p=371698

Handling an application’s state, or state management, plays an essential role in creating dynamic and responsive user interfaces and effectively executing business logic.

React offers numerous state management methods for storing and updating data, making it a popular web development technology.

Think of it like different ice cream flavors: some people like chocolate (Redux), some like vanilla (Recoil), and some like strawberry (MobX). With React, developers can select the flavor that best suits their needs and projects.

React allows developers the flexibility to select how best to organize their code, whether that means keeping things simple using React Hooks or putting everything in one location with Redux.

It is like having a bunch of ice cream toppings; it makes development flexible and enjoyable! 

 

 

Picture1

 

 

Choosing an appropriate state management library for your React application involves considering various aspects. When making your choice, consider the following crucial factors: 

 

Picture7

 

 

Let’s discuss some of the popular state management libraries and patterns in the React ecosystem:

State Management

 

Let’s dive deeper into these popular state management libraries.

Redux 

For developers, Redux is like a superhero, especially when they are creating large, complex programs. This amazing tool assists with tracking everything that occurs within your app, much like a superhero watching over the whole city. Redux provides a special store to store all your project data.

The best feature is that no component can just modify things in this store at random; instead, they must notify Redux of what needs to be done by sending a message known as an action. Everything becomes easier to understand and more predictable as the outcome. 

One key advantage of Redux is its seamless integration with React, a popular framework in web development. By combining these two technologies, developers can ensure the smooth functioning of their applications and easily address any issues that may arise.

Think of Redux as a reliable guide for managing your app’s state, simplifying the process, and preventing you from getting overwhelmed by its complexity.  

Here are some Key concepts in Redux. These concepts work together to establish a structured and predictable framework that ensures systematic management of data flow and application state. 

Key Concept in Redux

Recoil

Recoil is an experimental state management library developed by Facebook that provides a powerful solution for handling states in React applications, particularly for small-to-medium-sized projects.

It enhances the capabilities of the basic React framework and offers a group of features that can be tough to accomplish with React alone. 

Recoil’s flexibility and adaptability in managing state are key advantages, especially when dealing with components. It allows developers to handle the state in ways that meet a project’s specific needs.

Recoil simplifies managing data in React, making complex state handling effortless. It is like having a handy tool that takes the stress out of managing your application’s data.

For more information about Recoil, you can check out my upcoming blog. 

React Hooks 

The introduction of React Hooks in React version 16.8 in February revolutionized state management in functional components. Before Hooks, the handling state of functional components was limited, and class components were mainly used. 

The useState Hook is the primary component of Hooks, allowing simple state management within functional components.

Furthermore, react offers additional Hooks for particular use cases and advanced functionality, enhancing the overall development experience and increasing state management flexibility. 

Below are a few of the most used React hooks for state management. 

 

most popular

Context API 

A built-in feature of React called the Context API makes it easier to maintain a local state within a component tree and allows the state to be shared globally without having to be explicitly sent down through props.

It is frequently used to update and provide easy access to states for components located further down the component tree and to manage states at higher levels of the component tree. 

Context Object

It was made with createContext and comes with a provider and a consumer for sharing state management. 

Supplier: wraps components to provide context. 

Consumer: Accesses the component’s context value. 

Default Values: Provides a default value for components outside a provider’s scope when the context is created. 

Nested Contexts: Allows the nesting of multiple contexts, each with a separate provider and consumer. 

Dynamic Context Updates: This enables the context value to be updated dynamically based on the component’s logic or state. 

Performance Optimization: Optimizes rendering and avoids needless re-renders using techniques such as React. Memo. 

 

MobX

React developers can use MobX, a useful tool, to manage the dynamic data in their projects. Like a manager operating in the background, it ensures that the user interface (the user interface) updates automatically when data changes.

It is beneficial for clean, scalable state management for your app. 

It simplifies the process of tracking changing data, which is essential in React. MobX lets you specify certain areas of your data (or state) to be tracked and updates the display whenever those parts change.  

MobX is a helpful utility that monitors the data in your app and ensures that everything remains coordinated without requiring you to update the UI (User Interface) manually whenever something changes.

It is a clever approach to dealing with React application state management problems. 

You can refer to the official MobX documentation at https://mobx.js.org/  for further information and advanced usage. 

Zustand 

Zustand is a helpful tool for React, making it easier to manage and control the data in your applications.

It is known for being straightforward and not overly complex, yet despite this, it still has a lot of powerful features for managing how things are stored and updated in React.

It functions similarly to a straightforward and reliable helper in managing the data in your application. It is a lightweight yet powerful alternative to other state management solutions like Redux or MobX. 

Below are a few key points about Zustand worth noting. 

Zustand

 

Jotai 

For React apps, Jotai is a simplified state management solution that offers an option to more well-known tools like Redux and Context API. Its easy-to-use API and lightweight design make it attractive for developers looking for a simple state management solution. 

Jotai is made to work well with small or big applications and is easy to integrate into projects. It has a cool feature called atoms and derived atoms that make handling state simple and improve the overall development experience. 

With a focus on simplicity, Jotai presents a concise API, unveiling just a few exports from its main bundle. 

Atom’ is used to create fundamental states without assigned values, and ‘useAtom’ helps in managing states within React components. ‘createStore’ is the core of state management in Jotai, acting as a pivotal point.

The ‘Provider’ connects components, enabling the sharing of state details and simplifying communication across various project parts. This approach indeed offers a straightforward method for managing state in React applications. 

In summary, React provides a variety of state management libraries to cater to different requirements. Whether you value Redux for its established dependability, MobX for its simplicity, or Recoil for its contemporary approach, every project has an option. The crucial aspect is to select the most suitable option for your project and what your team is comfortable with. By thoroughly evaluating the factors mentioned in the blog, you can confidently opt for the most appropriate state management solution for your React applications. 

 

Here are the official websites where you can find more information about the state management libraries and React features we discussed. 

Redux: https://redux.js.org/ 

Recoil: https://recoiljs.org/ 

React Hooks: https://reactjs.org/docs/hooks-intro.html 

Context API: https://reactjs.org/docs/context.html 

MobX: https://mobx.js.org/README.html 

Zustand: https://github.com/pmndrs/zustand 

Jotai: https://github.com/pmndrs/jotai  

Plus, stay tuned for my upcoming blogs to dive deep into the world of state management! 

]]>
https://blogs.perficient.com/2024/11/14/introduction-to-state-handling-excellence-in-react-a-developers-perspective/feed/ 1 371698
Enhancing TypeScript Code with Generics https://blogs.perficient.com/2024/03/12/enhancing-typescript-code-with-generics/ https://blogs.perficient.com/2024/03/12/enhancing-typescript-code-with-generics/#respond Tue, 12 Mar 2024 05:26:08 +0000 https://blogs.perficient.com/?p=358884

In this blog, we will explore generics in TypeScript, but before diving into generics, let’s first understand what TypeScript is and why TypeScript has become increasingly popular in the software development industry. 

So, what is TypeScript?

TypeScript, as a free and open-source high-level programming language, acts as a superset of JavaScript by introducing features like interfaces, enums, and type annotations. 

Its main benefit is that it can discover errors early in the development process, identifying potential problems and data types before the code is executed. This proactive strategy helps developers prevent runtime errors and improves code predictability. 

The flexibility of TypeScript is a major characteristic, and features like generics and union types are essential. To make the most of TypeScript’s flexibility, it’s important to know the distinctions between union types and generics. These features improve TypeScript’s efficiency in handling types. 

Union Types and Generics:

Picture1

In TypeScript, generics enable you to write code that can work with various data types without specifying them in advance, unlike unions, where specific types must be predefined. Generics specify the data type when the code is executed, providing greater adaptability and abstraction than unions. 

Several Significant Advantages of Generics Include:

Type Safety: By providing type safety at compile-time in this statically typed language, generics provide a way to write flexible code while supporting type safety. 

Reusability of Code: Generics make it possible to write flexible, reusable code for a variety of types, which minimizes duplication and improves maintainability. 

Better Maintainability and Readability: Generics allow writing code that conveys meaning without being restricted to specific types, which results in more maintainable and readable code with clear and flexible logic for various situations. 

So, let’s see the syntax of generics:

Here’s an Example of How to Implement the Generic Type in TypeScript: 

Example of generics

This TypeScript code defines a generic function named message that takes an input of any type (T) and returns the same type. The function is then used twice, first with a string input (“Hello, typescript!”) and second with a number input (123456). 

The generic function ensures type safety, allowing the returned values to maintain their original types. The resulting output successfully uses the generic function with string and number inputs, printing “Hello typescript!” and 123456, respectively. 

Let’s See Another Example of Generics: 

Example of Generic

The above example is created to swap the values of two variables while supporting type safety. It accepts two parameters of the same generic type, T, and swaps the values in a tuple [T, T]. 

In the above examples, the result of switching the numerical values 50 and 100 are stored in ReverseNumbers, giving the output [100, 50]. 

Similarly, ReverseString performs swapping of the string values “hello” and “generics,” producing the result [“generics”, “hello”]. 

Because of its generic nature, the function can handle a variety of data types while ensuring type correctness, making it versatile and reusable for value swapping. 

Let’s See More of the Workings of Generic:

The following illustration shows what TypeScript does when you call a generic function, such as message<T> (input: T): T and pass it as a string.

Workings of generic

In conclusion, enhancing TypeScript code with generics empowers flexible coding. Add them to your next code to make it more flexible and reusable and to ensure type safety while working with a variety of data types. 

 

Thanks for reading! 

]]>
https://blogs.perficient.com/2024/03/12/enhancing-typescript-code-with-generics/feed/ 0 358884
Setting up the Component Form Builder in Site Studio https://blogs.perficient.com/2023/07/12/setting-up-the-component-form-builder-in-site-studio/ https://blogs.perficient.com/2023/07/12/setting-up-the-component-form-builder-in-site-studio/#comments Wed, 12 Jul 2023 07:31:31 +0000 https://blogs.perficient.com/?p=339930

In the last blog, we get to know about how to create a component in the site studio.

In this blog, we are going to set up the component form builder for the component.

You can improve specific functionalities or enhance the visual appearance of your site by using component form builder. The component form builder is located below the layout canvas. To add fields to your Component forms, use Field elements. It can be built by clicking the plus button similar to the layout above with using fields instead of elements.

Building a Component Form Builder

Firstly, we need to add the tab container

Click on the plus button, first search for Tab Container from fields in the Sidebar browser, and drag and drop into the form builder.

 

form builder

 

Now choose Tab item fields and wrap them inside the Tab container. Renamed the tab item fields as Content.

Adding Text and Image

In the content field, you can add the text and image content inside this field, then add the field group inside it.

 

form builder

 

Also, by double-clicking on the field, you get to choose the Default state of the field as well as we have the settings of Visibility. Depending on the conditional logic placed into the field’s “Show field if” input, component form fields can be shown or hidden.

 

form builder

Connecting to the Right Field

Now we need to connect fields with the correct element, so double click on the Heading element from the layout canvas, then switch to toggle variable mode. Simply type the name of the field in the square bracket as shown in the below image. To switch out of variable mode, click the plus sign, it will return every field to its original form.

 

form builder

 

 

Also, add Field label and Machine name on form fields.

 

form builder

 

Layout and Style

Second, is the Layout and Style, here we need to add the stylings for components, for ex – Background color, border, outer padding, and Text / Image alignment which will be editable in the component, then do add the same above steps to enter tokens into the form fields.

 

form builder

 

 

Help Tab

And last is the Help, in this tab, we can add information or uses about the form elements, and this tab is totally optional.

 

form builder

 

 

Preview Form

And lastly, preview your component form in the Component form preview area to see how the form has been created.

 

form builder

 

 

Thanks for Reading!

]]>
https://blogs.perficient.com/2023/07/12/setting-up-the-component-form-builder-in-site-studio/feed/ 2 339930
How to Create a Component in Site Studio https://blogs.perficient.com/2023/02/21/how-to-create-a-component-in-site-studio/ https://blogs.perficient.com/2023/02/21/how-to-create-a-component-in-site-studio/#respond Tue, 21 Feb 2023 14:48:39 +0000 https://blogs.perficient.com/?p=328074

Site Studio is a Drupal product from Acquia which builds a low-code and component-based website with a simple drag-and-drop interface.

So, what is a component? Components are the mini templates to provide a flexible layout system to customize each section on the page as per requirements. This can be used by site builders in pages to create component-based layouts.  

Components can also be used by site builders in templates to take a component-based approach to create websites. This is a reusable object it can be used multiple times with different content on the pages. We can easily drag and drop these site studio components to create pages on websites.

So, let us see how to create a component Step-by-Step in the site studio

Step 1First, navigate to the Site studio menu from the admin menu, Site Studio -> Components -> Components –> and click on Add components.

       Picture1

 

 Step 2 – Then, we need to fill in the details of our components. Add Component Title, choose a category to which category it belongs to, and add Preview image, which is a thumbnail in the sidebar browser.

 

Picture2

 

      Tip: There are some component naming conventions we need to take into consideration

    • Use camel case to write component names to keep consistency. 
    • It is not necessary to include “component” in the name.

 

Step 3 – Next, we have the layout canvas, layout canvas is a drag-and-drop interface for structuring layouts. Here we build our layout of the component by using the Elements. 

 Site Studio provides diverse types of drag-and-drop elements which are: 

  • Content elements 
  • Layout elements 
  • Media elements 
  • Interactive elements 
  • View elements 
  • Menu elements 
  • Drupal core elements 

 For more information about using these Elements, you can refer to this Document    

 Now, click on the “+ plus” button and drag and drop the elements according to your component. 

 

Picture3

 

First, drag the Layout elements inside it. 

 

Picture4

 

Step 4 – Now comes the styling part, by using the style tab, you can give stylings to your component. Double-click on the element and you can see all the settings.

In the properties tab, you can get all the CSS styles as well as we have the option of custom CSS. 

Tip: Better to use a full-width container first and a boxed-width container to center rather than using any CSS stylings to center the component.  

 

Picture5

 

Step 5 – Next, we need to add the actual content element. Add the elements from the sidebar browser according to your component, here also you can add the styling from the properties tab by double-clicking on the elements.

 

Picture6

 

Step 6 – Now, create the component form, and preview your component form in the Component form preview area to see how the form has been created. And save it as a component by simply clicking “Save and continue.”

For more information about the component form builder, you can check my upcoming blog on the Component form builder. 

Step 7 – Add your component to a page that has a Layout canvas. Now, drag and drop it into the layout and double-click on the Component to edit its settings and add the content inside it

 

Picture8

 

Lastly, Save and Preview your page. And now your Site Studio component is ready. 

 

Picture7

 

Thanks for reading! 

 

]]>
https://blogs.perficient.com/2023/02/21/how-to-create-a-component-in-site-studio/feed/ 0 328074