Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How are React Hooks different from class components in ReactJS?
Next article icon

How Relay is different from Redux ?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Redux is an open-source JavaScript library for state management in applications, commonly integrated with React or Angular. As the official React binding for Redux, React Redux enables components to interact with a centralized Redux Store, facilitating scalable state management through a unidirectional data flow model.

There are 3 major components of Redux:

  • Store: It contains the state of components that can be passed to other components in the application.
  • Actions: It basically contains the actions that can be performed on the states present in the store.
  • Reducers: These are the pure functions that contain operations that need to be performed on the state.

Syntax:

import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
export default store;

Steps for installing & configuring the Redux

Step 1: Create a React App using the following command:

npx create-react-app redux-example

Step 2: Now get into the project directory:

cd redux-example

Step 3: Install the Redux libraries using the following command:

npm install redux react-redux

Step 4: Importing the required components:

import { useSelector, useDispatch } from 'react-redux';

Step 5: Create a new folder redux inside the src folder.

mkdir src/redux

Step 6: Create a new file actions.js in the redux folder.

touch src/redux/actions.js

Step 7: Create a new file reducers.js in the redux folder.

touch src/redux/reducers.js

Step 8: Create a new file store.js in the redux folder.

touch src/redux/store.js

Project Structure: 

reduxfolder.PNG
Project Structure

Example: Below is the code example of the using redux.

JavaScript
//action.js export const increment = () => {     return {         type: 'INCREMENT'     }; }; export const decrement = () => {     return {         type: 'DECREMENT'     }; }; 
JavaScript
//reducers.js  const initialState = {     count: 0 }; const reducer = (state = initialState, action) => {     switch (action.type) {         case 'INCREMENT':             return {                 ...state,                 count: state.count + 1             };         case 'DECREMENT':             return {                 ...state,                 count: state.count - 1             };         default:             return state;     } }; export default reducer; 
JavaScript
//store.js  import { createStore } from 'redux'; import reducer from './reducers'; const store = createStore(reducer); export default store; 
JavaScript
//App.js  import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement } from './redux/actions'; import './App.css'  function App() {     const count = useSelector((state) => state.count);     const dispatch = useDispatch();     return (         <div className="App">             <button onClick={() => dispatch(decrement())}>                 -             </button>             <h1>{count}</h1>             <button onClick={() => dispatch(increment())}>                 +             </button>         </div>     ); } export default App; 
JavaScript
//index.js  import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './redux/store'; import App from './App'; import './index.css';  ReactDOM.render(     <Provider store={store}>         <App />     </Provider>,     document.getElementById('root') ); 
CSS
/* Write CSS Here */  .App {     display: flex;     flex-direction: column;     justify-content: center;     align-items: center; }  body {     background-color: antiquewhite; }  .App>h2 {     text-align: center;     font-size: 2rem; }  .App>button {     width: 20rem;     font-size: larger;     padding: 2vmax auto;     height: 2.6rem;     color: white;     background-color: rgb(34, 34, 33);     border-radius: 10px; }  button:hover {     background-color: rgb(80, 80, 78);  } 

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000

counterGIF

Relay:

Relay is a data management library for React that lets you fetch and update data with GraphQL. It works closely with GraphQL APIs and optimizes data fetching by using a declarative approach and a concept called GraphQL fragments. React Relay is basically a framework used to build GraphQL-driven React applications. It keeps the management of data-fetching easy, no matter how many components your React app has.

Syntax:

import { RelayEnvironmentProvider } from 'react-relay/hooks';

Steps for installing & Configuring the Relay

Step 1: Installing a React App

npx create-react-app relay-example

Step 2: Now, we need to fetch the data from the GraphQL servers. For this, we will use the fetch API to request some data from the GitHub GraphQL API, and we will use it as a server.

To start, we will need an authentication key token for the GitHub API. Follow these steps:

  • Go to github.com/settings/tokens
  • Ensure that the latest repo scope is selected
  • Generate a unique token and store it for your use

Step 3: Navigate to the main directory of your project

cd relay-example

Step 4: Now, we will fetch GraphQL from React. We can use the fetchGraphQL function to fetch some data in our React App.

async function fetchGraphQL(text, variables) {
const REACT_APP_GITHUB_AUTH_TOKEN =
process.env.REACT_APP_GITHUB_AUTH_TOKEN;
// Fetch data from GitHub's GraphQL API:
const response =
await fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {
Authorization: `bearer ${REACT_APP_GITHUB_AUTH_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: text,
variables,
}),
});
// Get the response as JSON
return await response.json();
}
export default fetchGraphQL;

Step 5: Install the react-relay dependencies with the following commands:

npm install --save relay-runtime react-relay
npm install --save-dev relay-compiler babel-plugin-relay
OR
yarn add relay-runtime react-relay
yarn add --dev relay-compiler babel-plugin-relay

Step 6: Create a GraphQL Schema

Create a file named schema.graphql in the root of your project. Copy the schema from GitHub's GraphQL API documentation or use a sample schema from a public GraphQL API.

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-relay": "^15.0.0",
"react-scripts": "5.0.1",
"relay-runtime": "^15.0.0",
"web-vitals": "^2.1.4"
}

Example: Below is the code example using Relay

JavaScript
import React from 'react'; import './App.css'; import graphql      from 'babel-plugin-relay/macro'; import {     RelayEnvironmentProvider,     loadQuery,     usePreloadedQuery, } from 'react-relay/hooks'; import RelayEnvironment from './RelayEnvironment';  const { Suspense } = React;  // Define a query const RepositoryNameQuery = graphql`   query AppRepositoryNameQuery {     repository(owner: "facebook", name: "relay") {       name     }   } `;  // Immediately load the query as our app starts. const preloadedQuery =      loadQuery(RelayEnvironment, RepositoryNameQuery, {     /* query variables */ });  // Inner component that reads the preloaded  // query results via `usePreloadedQuery()`. function App(props) {     const data =         usePreloadedQuery(RepositoryNameQuery, props.preloadedQuery);     return (         <div className="App">             <header className="App-header">                 <p>{data.repository.name}</p>             </header>         </div>     ); }  // <RelayEnvironmentProvider> tells child components  // how to talk to the current // Relay Environment instance // <Suspense> specifies a fallback in case a child suspends. function AppRoot(props) {     return (         <RelayEnvironmentProvider environment={RelayEnvironment}>             <Suspense fallback={'Loading...'}>                 <App preloadedQuery={preloadedQuery} />             </Suspense>         </RelayEnvironmentProvider>     ); } export default AppRoot; 
JavaScript
//RelayEnvironment.js  import { Environment, Network, RecordSource, Store }      from 'relay-runtime'; import fetchGraphQL from './fetchGraphQL';  // Relay passes a "params" object with the query name and text. // So we define a helper function // to call our fetchGraphQL utility with params.text. async function fetchRelay(params, variables) {     console.log(`fetching query ${params.name}                  with ${JSON.stringify(variables)}`);     return fetchGraphQL(params.text, variables); }  // Export a singleton instance of Relay  //Environment configured with our network function: export default new Environment({     network: Network.create(fetchRelay),     store: new Store(new RecordSource()), }); 

Step to Run Application: Compile Relay Queries

Run the Relay compiler to generate artifacts for your queries:

npm run relay or npm start

Output: Now open your browser and go to http://localhost:3000

relayoutput.PNG

Difference between Relay and Redux:

Property

Relay

Redux

PurposeA GraphQL client framework for data fetching and caching.A React state management library for storing and managing application state.
Data FetchingDeclarative data fetching using GraphQL queries and fragments.Manual data fetching using actions and reducers.
Store StructureHierarchical store structure based on the GraphQL Schema.Flat store structure with reducers managing different parts of the state.
PerformanceOptimized data fetching and caching with GraphQL.The performance depends on application design and usage patterns.
Component BindingUses container components and HOCs for data binding.Uses hooks like useDispatch() and useSelector() for handling state.
ComplexityCan be complex and requires an understanding of GraphQL.Relatively simpler, can be used easily in smaller applications.



Next Article
How are React Hooks different from class components in ReactJS?
author
aryan143jbr
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Questions
  • Web Technologies - Difference Between

Similar Reads

  • How does Redux Saga Differ from Redux Thunk ?
    In Redux, middleware plays a crucial role in managing asynchronous actions. Redux Saga and Redux Thunk are two popular middleware libraries used for handling side effects in Redux applications. While both serve similar purposes, they differ significantly in their approach and capabilities. In this a
    5 min read
  • Do Hooks replace Redux?
    React Hooks and Redux serve different purposes, but they can be used together or independently based on your application's needs. Redux is a state management library, while React Hooks provides states with a way to manage local state and lifecycle events within functional components. Let's explore t
    2 min read
  • How are React Hooks different from class components in ReactJS?
    React Hooks are helpful tools that make building websites and apps with React easier. They simplify how users handle things like data and app behavior, making the code cleaner and easier to understand. Class components in React are like the old-school way of building parts of your website or app. Th
    2 min read
  • How does Redux Toolkit simplify Redux development?
    Redux is a powerful state management library for JavaScript applications, but setting it up and managing boilerplate code can be cumbersome. Redux Toolkit is an official package from the Redux team designed to streamline Redux development and reduce boilerplate code. In this article, we'll explore h
    6 min read
  • How to Create Store in React Redux ?
    React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently. Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a def
    4 min read
  • What is a store in Redux ?
    In Redux, the store is the central where all the state for the application is stored. This ensures the state is predictable and persistent for the entire application. is the central component for handling the state for the Redux application. Basics of Redux StoreThe Redux store is the heart of state
    6 min read
  • How does a Pure Component Differ from a Regular Component ?
    In React, components are the building blocks of user interfaces. They encapsulate the UI logic and render the UI elements based on the input data. React offers different types of components, including regular components and Pure Components. Table of Content Components in ReactRegular ComponentsBenef
    4 min read
  • How ReactJS ES6 syntax is different compared to ES5 ?
    Both ES6 and ES5 are Javascript scripting languages in the development industry. ECMA Script or ES is a trademarked scripting language made by ECMA International. The European Computer Manufacture Association or ECMA is used for client-side scripting for the worldwide web. ES5 was released in 2009 a
    6 min read
  • How does Redis store data?
    Redis is an in-memory data store, meaning it stores data primarily in memory (RAM) for extremely fast read and write operations. It organizes data using key-value pairs, where keys are unique identifiers, and values can be of various types such as strings, lists, sets, sorted sets, hashes, bitmaps,
    3 min read
  • How to Handle Forms in Redux Applications?
    Handling forms in Redux applications involves managing form data in the Redux store and synchronizing it with the UI. By centralizing the form state in the Redux store, you can easily manage form data, handle form submissions, and maintain consistency across components. We will discuss a different a
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences