Tuesday, June 3, 2025
News PouroverAI
Visit PourOver.AI
No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
News PouroverAI
No Result
View All Result

Using Crystalize.js with React for dynamic state management

October 31, 2023
in Front-Tech
Reading Time: 5 mins read
0 0
A A
0
Share on FacebookShare on Twitter



State management is an important concept in modern app development, especially for single-page applications. It is used to control and monitor actions, user inputs, and server responses. Popular libraries like Redux and MobX are often used by developers to manage state in React applications. However, these libraries primarily provide a way to access data globally without the need to pass props between components and pages. Unfortunately, they do not offer functionality for undoing or redoing actions in an application, or navigating to specific points in a series of actions. This is where the Crystalize.js library comes in. In this article, we will explore the Crystalize.js library and learn how to use it with React by building a photo editing web app with undo, redo, and download features. We will also compare it to Redux to understand its similarities and differences. You can find the source code for our demo project on GitHub. By the end of this tutorial, we will have an app that functions as shown in the video below: What is Crystalize.js? Crystalize.js is a library specifically designed for dynamic state management. It captures actions and data as “shards” and stores them in a state called a “crystal”. But what does this all mean? Interestingly, due to the way Crystalize.js handles data, it enables us to do things that are not possible with other reducers and state management solutions. For example, we can implement undo and redo functionality in an application. Because of this unique approach to state management, Crystalize.js introduces new terms such as crystalizer, crystal, shards, and base. It also provides a set of APIs including take, leave, with, focus, and more. Instead of explaining these terms upfront, we will discuss them in detail while working on our demo project in the following sections. This will give us a more practical understanding of the library and how it works. Setting up a React application with Crystalize.js To dive into Crystalize.js, we will set up a React app using the Next.js CLI. Let’s start by creating a new folder for our project. You can choose any name for the folder. For this tutorial, I will name it “dynamically-manage-state-with-crystalize-js”. Next, open the folder in a code editor like VS Code. In your terminal, run the following command: npx create-next-app@latest Follow the prompts to set up your project. Once it is set up, install the Crystalize.js library by running the following command: npm i crystalize.js You will also need to install helper libraries for converting an HTML file to an image, downloading the converted image, and getting icons. You can do this by running the following command: npm i html-to-image downloadjs react-icons Then, create “components” and “crystalizer” folders in the “src” directory. Additionally, create the following .jsx files in the “components” folder: canvas.jsx download-button.jsx edit-tool-list.jsx editor.jsx image-uploader.jsx range-input-field.jsx redo-button.jsx select-field.jsx sidebar.jsx text-field.jsx tool-list-item.jsx undo-button.jsx Lastly, create a “state.jsx” file in the “crystalizer” folder. At this point, your project folder structure should look similar to this: // Folder structure ┣ public ┃ ┣ favicon.ico ┃ ┣ next.svg ┃ ┗ vercel.svg ┣ src ┃ ┣ components ┃ ┃ ┣ canvas.jsx ┃ ┃ ┣ download-button.jsx ┃ ┃ ┣ edit-tool-list.jsx ┃ ┃ ┣ editor.jsx ┃ ┃ ┣ image-uploader.jsx ┃ ┃ ┣ range-input-field.jsx ┃ ┃ ┣ redo-button.jsx ┃ ┃ ┣ select-field.jsx ┃ ┃ ┣ sidebar.jsx ┃ ┃ ┣ text-field.jsx ┃ ┃ ┣ tool-list-item.jsx ┃ ┃ ┗ undo-button.jsx ┃ ┣ crystalizer ┃ ┃ ┗ state.jsx ┃ ┣ pages ┃ ┃ ┣ api ┃ ┃ ┃ ┗ hello.js ┃ ┃ ┣ _app.jsx ┃ ┃ ┣ _document.jsx ┃ ┃ ┗ index.jsx ┃ ┗ styles ┃ ┃ ┣ Home.module.css ┃ ┃ ┗ globals.css ┣ .gitignore ┣ README.md ┣ jsconfig.json ┣ next-env.d.ts ┣ next.config.js ┣ package-lock.json ┣ package.json ┗ tsconfig.json After setting up the folders, we will open the “src/crystalizer/state.jsx” file and start exploring the Crystalize.js library. Setting up the Context API Since Crystalize.js does not provide global state management, we will set it up using the React Context API. To do this, add the following code to the “src/crystalizer/state.jsx” file: import { createContext, useContext } from ‘react’; // Initialize context const EditImageContext = createContext(null); // Context provider export const EditImageContextProvider = ({ children }) => { return ( {children} ); }; // Hook to access the data in the context export const useEditImage = () => { const context = useContext(EditImageContext); if (!context) { throw new Error(‘Use edit image context is missing’); } return context; }; Now that we have set up the Context API, we need to wrap the part of the application where we want to share the context with the Provider. In our case, it is the Home page. Here is an example of how to do this: // src/pages/index.js import React from ‘react’; import { EditImageContextProvider } from ‘../crystalizer/state’; const Home = (props) => { return ( {/** Other components will go here **/} ); }; export default Home; We are now ready to use Crystalize.js in our React project. Let’s get started. Initializing Crystalize.js To start using Crystalize.js in our React project, we need to import the library in the “src/crystalizer/state.jsx” file and call the Crystalizer class with the appropriate arguments. It is important to note that the initialData object contains the id and style keys: // src/crystalizer/state.jsx import { createContext, useContext, useRef, useCallback, useState, useMemo } from ‘react’; import Crystalizer from ‘crystalize.js’; import { toPng } from ‘html-to-image’; import download from ‘downloadjs’; // Initialize context const EditImageContext = createContext(null); export const initialData = { style: { width: 400, // px height: 400, // px blur: 0, // px brightness: 100, // % contrast: 100, // % grayscale: 0, // % ‘hue-rotate’: 0, // deg invert: 0, // % opacity: 100, // % sepia: 0, // % scale: 1, // number ‘object-fit’: ‘none’, // fill, contain, cover, none, scale-down }, id: 1, }; let crystalizerInitializer = new Crystalizer({ initial: initialData, reduce: (crystal, shard) => { return { id: shard.id + crystal.id, style: shard.style }; }, }); // Context provider //… Let’s break down the code above: After importing the necessary dependencies and setting up some styles for our initialData, we create a crystalizerInitializer variable that creates a new Crystalizer. The Crystalizer class requires two mandatory keys: initial and reduce. It can also accept additional optional keys such as map, sort, tskey, and keep. In general, you should pass an object with at least one unique value as the initialData. This helps structure your crystals and store your shards effectively. In the code above, we passed the initialData to the initial key. Additionally, we passed a callback function with two parameters to the reduce key. The crystal parameter represents the initial data passed to the Crystalizer class, while the shard represents the current item passed to the crystalizer engine from our application at any given time. We expect the callback in the reduce key to return the values that will be added to the app’s main crystal. Setting up states Since we are building a photo editing app with undo and redo features, we need to define an imageRef and four states. We will also set up a fifth state to extract the content of the crystalizer properly in the context provider. Here is how we will do this: // src/crystalizer/state.jsx const imageRef = useRef(); const [imageUrl, setImageUrl] = useState(”); const [crystalizer, setCrystalizer] = useState(crystalizerInitializer); const [modifier, setModifier] = useState(‘width’); const [pointer, setPointer] = useState(0) const [crystal, shards, base] = crystalizer.leave(pointer).take(1); Let’s understand what is happening here: The imageRef object captures the container of the image and allows it to be downloaded. The imageUrl state holds the URL of the locally uploaded image. The crystalizer state holds the crystalizerInitializer and any subsequent updates to the crystalizer. The modifier state holds the aspect of the image style that the user chooses to modify. In the code above, it is set to ‘width’. The pointer state holds a value that can be passed to the .leave method to determine the number of shards to remove from the crystalizer. In the code above, it is set to 0. Lastly, the fifth state returns the crystal, shards, and base variables by calling the crystalizer.leave(N).take(N) method. The .leave method excludes a certain number of shards from the result, and the .take method selects a certain number of shards from



Source link

Tags: Crystalize.jsdynamicManagementReactState
Previous Post

Protect your web apps from modern threats with Microsoft Defender for Cloud

Next Post

Dutch regulator disputes Apple’s commissions in dating app case By Reuters

Related Posts

The essential principles of a good homepage
Front-Tech

The essential principles of a good homepage

June 7, 2024
How to measure and improve user retention
Front-Tech

How to measure and improve user retention

June 6, 2024
Push Animation on Grid Items
Front-Tech

Push Animation on Grid Items

June 5, 2024
How to build a Rails API with rate limiting
Front-Tech

How to build a Rails API with rate limiting

June 4, 2024
Introduction to the B.I.A.S. framework
Front-Tech

Introduction to the B.I.A.S. framework

June 3, 2024
Blue Ridge Ruby is exactly what we need
Front-Tech

Blue Ridge Ruby is exactly what we need

June 3, 2024
Next Post
Dutch regulator disputes Apple’s commissions in dating app case By Reuters

Dutch regulator disputes Apple's commissions in dating app case By Reuters

Leveraging IBM Cloud for electronic design automation (EDA) workloads

Leveraging IBM Cloud for electronic design automation (EDA) workloads

This AI Paper Reveals: How Large Language Models Stack Up Against Search Engines in Fact-Checking Efficiency

This AI Paper Reveals: How Large Language Models Stack Up Against Search Engines in Fact-Checking Efficiency

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Trending
  • Comments
  • Latest
Is C.AI Down? Here Is What To Do Now

Is C.AI Down? Here Is What To Do Now

January 10, 2024
Accenture creates a regulatory document authoring solution using AWS generative AI services

Accenture creates a regulatory document authoring solution using AWS generative AI services

February 6, 2024
Managing PDFs in Node.js with pdf-lib

Managing PDFs in Node.js with pdf-lib

November 16, 2023
23 Plagiarism Facts and Statistics to Analyze Latest Trends

23 Plagiarism Facts and Statistics to Analyze Latest Trends

June 4, 2024
Azul cloud service spots dead code in Java apps

Azul cloud service spots dead code in Java apps

October 7, 2023
The 15 Best Python Courses Online in 2024 [Free + Paid]

The 15 Best Python Courses Online in 2024 [Free + Paid]

April 13, 2024
Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

June 10, 2024
AI Compared: Which Assistant Is the Best?

AI Compared: Which Assistant Is the Best?

June 10, 2024
How insurance companies can use synthetic data to fight bias

How insurance companies can use synthetic data to fight bias

June 10, 2024
5 SLA metrics you should be monitoring

5 SLA metrics you should be monitoring

June 10, 2024
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

June 10, 2024
Facebook Twitter LinkedIn Pinterest RSS
News PouroverAI

The latest news and updates about the AI Technology and Latest Tech Updates around the world... PouroverAI keeps you in the loop.

CATEGORIES

  • AI Technology
  • Automation
  • Blockchain
  • Business
  • Cloud & Programming
  • Data Science & ML
  • Digital Marketing
  • Front-Tech
  • Uncategorized

SITEMAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2023 PouroverAI News.
PouroverAI News

No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing

Copyright © 2023 PouroverAI News.
PouroverAI News

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In