React JS

redux toolkit

&

API communication

Redux

What is Redux?

  • A state management library for JavaScript applications.
  • Centralizes application state in a single store.
  • Single source of truth
  • State is read-only
  • Changes are made with pure functions (reducers)

Core Principles:

Redux Toolkit (RTK)

What is Redux Toolkit?

  • A set of tools and best practices for Redux development.
  • Simplifies Redux setup and reduces boilerplate code.
  • ​createSlice
  • configureStore
  • createAsyncThunk

Key Features:

How to Add it ?

  • installing libraries
npm install @reduxjs/toolkit react-redux
  • generate store
// src/app/store.js
import { configureStore } from '@reduxjs/toolkit';

export const store = configureStore(/* configuration */);
  • Provide it to the app
// App.jsx
import { Provider } from 'react-redux';
/* rest of the code /*
return <Provider store={store}> <App/> </Provider>

using a slice

  • A slice represents a piece of the Redux state and the reducers that update it.
// src/features/user/userSlice.js
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  name: '',
  email: '',
};

/* slice code */

export const { setUser, clearUser } = userSlice.actions;
export default userSlice.reducer;
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUser: (state, action) => {
      state.name = action.payload.name;
      state.email = action.payload.email;
    },
    clearUser: (state) => {
      state.name = '';
      state.email = '';
    },
  },
});

Adding slice to stor

import userReducer from '../features/user/userSlice';

export const store = configureStore({
  reducer: {
    user: userReducer,
  },
});

Hooks for context usage

you can make hooks to improve readability of the code to have better experience with RTK

import { useSelector, useDispatch } from 'react-redux';
import { setUser, clearUser } from './features/user/userSlice';

function useUser(){
	const user = useSelector((state) => state.user);
     const dispatch = useDispatch();
     return {
     	user,
        setUser:(newUser)=> dispatch(setUser(newUser))
        clearUser:()=> dispatch(clearUser())
     };
}

API Communications

How to communicate in react with API

React typically communicates with APIs using the following methods:

HTTP Requests:

  • fetch: A built-in JavaScript function for making HTTP requests.
  • Axios: A popular third-party library that simplifies making HTTP requests and handling responses.

WebSockets

  • For real-time communication, often using libraries like socket.io-client.

GraphQL

    • Using libraries like Apollo Client to manage GraphQL queries and mutations.

State Management Libraries

  • Redux Thunk or Redux Saga: Middleware for handling asynchronous actions in a Redux store.
  • React Query: For data fetching, caching, synchronization, and server-state management.

Using fetch

import React, { useEffect, useState } from 'react';

export default function MyComponent()  {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error);
        setLoading(false);
      });
  }, []);
  // part 2
};
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {data && data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
part 2

Using Axios

import React, { useEffect, useState } from 'react';
import axios from 'axios';

export default function MyComponent()  {
   const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then((response) => {
        setData(response.data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error);
        setLoading(false);
      });
  }, []);
  // part 2
};
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {data && data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
part 2
  • installing libraries
npm install axios

Using React Query

  • installing libraries
npm install @reduxjs/toolkit react-redux
  • generate context
import { QueryClient } from '@tanstack/react-query';
const queryClient = new QueryClient();
  • Provide it to the app
// App.jsx
import {  QueryClientProvider } from '@tanstack/react-query';
/* rest of the code /*
return <QueryClientProvider client={queryClient}>
	<App/>
</QueryClientProvider>
  • installing libraries
npm install @tanstack/react-query

Using React Query

import React, { useEffect, useState } from 'react';

export default function MyComponent()  {
   const { data, error, isLoading } = useQuery({ queryKey: ['fetchData'], queryFn: fetchData });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>
  		Error: {error.message}
    </div>;

  return (
    <div>
      {data && data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
};
import axios from 'axios';

const fetchData = async () => {
  const { data } = await axios.get('https://api.example.com/data');
  return data;
};
  • Fetch function

React RTK

By Youcef Madadi

React RTK

  • 268