Introduction

  • Install npm and node.js.
  • Install Visual Studio Code which we will use as IDE for development.
  • Install following plugins and themes





  • Install following chrome extenions
    • React Dev Tools
    • Redux Dev Tools
      • To use extension redux dev tools add method ComposeWithevTools in store.js and apply Middleware as argument to it.
      • const create_store = createStore(
        RootReducer,
        initialState,
        composeWithDevTools(applyMiddleware(...middleware))
        );
      • ComposeWithDevTools acts as a proxy way to our extensions redux dev tools to access the data.
      • Remove this function in production Envirnoment.
        • Shows the current authReducer state.
  • Create project
    • npx create-next-app@latest
    • npx create-vite@latest {{project name}} —template react.
  • Vite
    • Vite is used as a package, Manager in react applications.
    • Vite is used to build the application with a light weight specification.
    • Vite helps to create small bundle of app to handle further deployments easily.
    • Vite Is a build provider, it helps to create a build with required files.
    • “Vite build” command is used to create a build in dist folder.
    • “Vite” Command is used to run the application in temp.
    • “Vite” command refers configuration from vite.config.js
      • Modules imported in vite.config.js Define its working, for example, if react is imported, then vite runs with react etc.
  • Check for latest react dependency in package.json
  • To install dependencies use “npm install”
  • To run “npm run dev”
  • Dev dependencies are dependencies that are used in development part, not production part.
    • This section is found in package.json
  • Scripts are used to provide shortcuts to commands in package.json.
  • Dependencies section shows prod dependencies.
    • React is a library for development in web and native user interfaces like android or ios etc.
    • React is used for providing right specification for developing web and ios/android implementations.
    • React is a library and not a framework.
      • Frameworks are built on Basis of An architecture.
      • Architecture define the data flow in an action
      • In our library, only concerned libraries are loaded to perform a task. These libraries are pre written.
      • User has control over application flow in library. In framework the principle of the “inversion of control” Applies. The framework dictate the flow of the application.
      • In angular, which is a framework, most of the things are taken care by framework such as collecting the data, Passing the data, Holding the data etc.
        • It is done by framework implicitly.
        • Framework provides implementation.
      • For library We have to include very supporting library on table to perform a task.
      • Libraries provide us with whole aspect at once.
      • Libraries load the entire framework Whether we have to use one functionality only.
  • In react, we will come across integrated libraries
    • React Redux
      • React binding for redux.
      • It is an integrated library to include redux environment In react.
      • Uses adapter or connector based implementation.
      • Used to connect to redux in react application
    • React moment
      • React component for the moment, data library.
      • Converts moment supported content to react, supported content.
  • “npm run dev” generates temporary build for us With same structure as dist folder
  • “div” with ID “root” Is the entry point via application is added by “CreateRoot(document.getElementById(“root”))”.
  • “Render” Method renders data on the browser.
  • Entire DOM is Replicated in the memory and shortest path, to element is found out.
    • This algorithm is written by Facebook in react Library.
  • It can go to Path and do the manipulation.
  • The technical word for replicated DOM is virtual DOM.
    • At First changes are made to the virtual DOM And then changes are made to the actual DOM.
    • The shortest trespath Is used to make changes in virtual DOM As well as original DOM.
  • react-dom is a package used to manage a virtual DOM.
  • Virtual dom Helps us to manipulate things faster.
  • To perform manipulations on virtual DOM react using an algorithm.
  • This helps us to faster update the actual dom In next step.
  • Component is responsible for handling unit amount of UI.
  • It should not split into multiple parts
    • The component is preferred mechanism in react,vue, Angular etc For solving the Coupling mechanism.
    • The UI of a component should not be fit into multiple parts.
  • We must have two parameters while developing components
    • Maintainability
    • Reusability
      • A change at one point is reflected everywhere.
  • We can handle or manage Enterprise applications easily using components using modularity.
  • There are two ways to build web application
    • Hold all relevant things at one place.
    • Follow modularity.
  • Earlier we Used to use the first approach Second approach that is modularity Follow distribution of responsibility, principle which is easier to manage.
  • Single monolithic applications are harder to manage than micro front ends.
  • Application journey starts from single monolithic single Page applications to micro frontends.
  • A module has following parts.
    • Components
    • Redux
    • Services
    • Utils
  • In react, there is no concept of module, but we divide our application in module and all modules combined together to form our enterprise application.
  • Each module is independent, micro front end.
    • These module can be used Independently in another application as well.
  • HTML pages(homepage content)are a part of core components.
    • jsx is Extension for pages in react.
    • Filenames start with uppercase.
  • raface command is used to create a react function based on component.
    • Install ES7+React/Redux/React native snippets by dsznader plug-in in vs code.
      • Use it once inside The Component file.
  • Import is used to access methods from library package, for example React from ‘react’ package.
  • Like in Java Lambda we have an arrow function.
  • Const is used to declare a value which we cannot change.
  • When we export a variable it can be accessed by other files.
  • Default allows the component to be default export of the file
  • Empty start and end tag are called as fragments.(“<>”).
    • They are used as container
    • Fragment are not rendered as elements.
  • A file Which define export component or supplies a components is named by First letter, Capital.
  • File which consumes the component, its name starts from a small case.
    • Main.jsx Is the entry point to our application.
  • In react class property defined inside an element refers from a ES6 specification i.e classes defined in Javascript.
    • To use CSS classes, use className property Inside elements.
  • CSS in child components override the CSS in parent components.
  • React on uses required dependences, hence build is small.
  • React Router DOM Is used to render components using dynamic routing in our web application.
    • When we need to route Between components on our DOM tree.
    • Help us to do routing At run time and make changes to main DOM.
    • On click of a link, we need to render our component.
  • By default, react, App comes only with, react and react DOM dependencies.
  • Index.jsx is referred with default folder, import, for example, router/index.jsx Will be imported from  router.
  • The purpose of root router is to hold the router for every module.
  • Routers are Responsible for defining the routes for our application, They are used to render the Components at run time.
    • Router are the Location pathways.
    • Helps us to make our application interactive.
    • Render things at runtime.
  • imrr Command helps to import router, route, And navlink from ‘react-router-DOM’
    • Stands for import react router.
    • Install extension Es7+react/redux/reactive-native snippet’s.
  • Router element work like switch case, as soon as Path is fired necessary Component is loaded.
    • We define switch condition In route element in Path property and expression in Path value.
  • To enable router We must define BrowserRouter element in our main.js in our application.
    •  BrowserRouter must be specified in main.js As it will be used application wide.
      • Enclose App element in router element.
      • Import BrowserRouter from react-router-dom.
        • Generally imported as Router.
    • BrowserRouter binds to the Router element in router component’s.
  • Application flow when we hit any page
    • First, it goes to the main.js where our routers are enabled.
    • Next, it goes to the App component.
      • Render the Header component there
      • Render RootRouter component if needed.
        • Works like a switch case And loads the root (“/“) router And necessary component based routers
      • Render Footer component.
  • Form handling
    • Render form over the necessary routing path.
    • Declare the state
      • We want To hold the data getting from the form.
      • We use state to maintain component data.
      • We have two roles for state usage and change.
        • Usage defines the consuming of data that is state data in our component.
        • State data is immutable.
        • From the change perspective The data is mutable.
        • From the usage perspective, state is immutable.
        • When state is usage, we consume the state or data.
      • State maintains the state of component. It holds the data For component.
      • The state is divided into two parts(Structure of state)
        • Data
        • Setter Function
          • When we set the value, we change the data.
    • Dealing with state.
      • Form handling is used to deal with the state.
        • Import state.
        • Declare the state specification
        • Consume the state.
      • We use useState() method Inside our component, which returns two variables formData and setFormData and creates a state.
        • formData is our state variable or state name
        • SetFormData is Function to Update the state.
        • SetFormData Is called with following parameters.
          • const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value })
            • ...formData : spread operator to copy the existing state.
              • ... is the spread operator that is used to fetch all the contents of an object.
              • Gives all the content of form data object
              • All default values are provided
            • e.target.name gets name of the field which had triggered the event.
            • e.target.value will bring the new value for that element.
        • The entire formData is replaced with new value using setFormData().
        • usage is our formData and change is our setFormData
        • setFormData is used to update state that is to change the data there, we have to use this setFormData function.
        • Add the name of HTML properties of form to the useState method. These are passed in as the default constructor to the method useState().
        • Destructure is Used to create a collection of related values and store them inside object in component.
          • var {name, email, password, password2} = formData;
          • This is done to consume the state.
        • Initially, state is immutable to change its value. We use setState() method.
          • We get setState Function from useState.
        • UseState() is a hook that allows us to add state to functional component.
          • useState() Returns an array with two elements, the current state and function to update it.
          • We use object data structure with key value pairs To assign elements to variables Which are passed as parameters to constructor of useState().
          • const [formData,setFormData] = useState({
            name: 'Gaurav',
            email: 'gaurav@example.com',
            password: 'password123',
            password2: 'password123'
            })
        • We cannot change state directly as it is immutable, so we use the setState() method to change its state.
    • Declaring the event, handlers
      • All events in react are handled Explicitly
        • In angular many events like on change are handled implicitly.
      • Events in elements are referred with e.
        • From e we get “target” object, which gives us its value and name.
      • onChange event
        • When we change any value, in form in any input controller.
        • Call setState method With formData and Event object.
        • When the content of input controller is changed, immediately, we are expecting to change the state that is new values should be stored in state.
      • onSubmit event
        • const onSubmit = e => {
          e.preventDefault();
          if (password !== password2) {
          console.log('Passwords do not match');
          } else {
          console.log('Form submitted successfully', formData);
          }
          }
        • Used to handle form submission.
        • On submit event, applies to form element and allows handling submission of the form.
      • Assign name attribute to all the input controllers in the form.
      • Assign onChange attribute to necessary Input controllers in form.
        • Until We add onChange attribute, the input controller is not mutable.
      • e.preventDefault()
        • Prevents the events default functionality.
        • For example, default form submission is overridden.
        • Angular does this implicitly.
  • Setting Proxy for backend Application
    • When we fire call to an API, we don’t need to use entire base urls For our calls.
    • When we make a change in base, URL of Backend application We only have to change proxy specification.Thus we Don’t have to make changes for all URL’s
    • We need to inform our react application of default URL Which we should use across our application.
      • We need to perform proxy setting for this information.
    • When we fire REST API calls They are automatically redirected to our proxy.
      • This is done implicitly by vite And react.
    • Add this setting in vite.config.js
      • export default defineConfig({
        plugins: [react()],
        server: {
        proxy: {
        '/api': {
        target: 'http://localhost:9500',
        changeOrigin: true,
        secure: false
        }
        }
        }
        })
    • To perform a REST API calls with backend server We use the axios library
      • Install using npm i axios 
      • axios create() gives us a new object to perform REST call.
      • axios is better than fetch API as it helps us to implicitly add our token specification.
      • const API = axios.create({
        baseURL: '/api',
        timeout: 10000,
        headers: {
        'Content-Type': 'application/json'
        }
        });
    • We have properties like URL, timeout, headers etc.
    • In fetch api we have to write Above properties for each and every call. We don’t get any option for direct, centralised configuration.In axios we have this advantage.
    • axios object adds headers to all it’s calls implicitly.
    • Once our axios object is defined We add interceptor.
      • It helps us to add tokens automatically in our REST API calls.
      • Tokens are Stored in our local storage.
        • Local storage is not blocked by security system.
        • Local storage is like cookies with following differences
          • Cookies have a size around 8KB, but in local storage, we get 5MB storage.
          • Cookies can store data in string format, but in case of local storage, we hold data in terms of key value pairs.
      • We Provide authorisation tokenIn request, interceptor.
      • We can add token while creating axios Object too but that will make it required for all the pages. We may not need token for pages like login, register, logout, hence we should use interceptor.
      • We can Handle multiple tokens also for different URL’s Using config URL Property interceptor.
      • axios request, interceptors, take parameter config, and error.
      • API.interceptors.request.use(
        (config) => {
        // Add any custom headers or logic here
        const token = localStorage.getItem('token');
        if (token) {
        config.headers['x-auth-token'] = `${token}`;
        }
        return config;
        },
        (error) => {
        return Promise.reject(error);
        }
        );
    • Next we create Service for URL where response from our axios object url is processed.
      • We add request related information in our request
        • Type
        • Path
        • Method
        • Description
        • RequestBody
      • Whenever we perform Rest call we hold above information.
    • Our call maybe synchronised or asynchronised
    • And for waiting for response we use "await"
      • It waits for response before proceeding further. For example, if we want to return response, we use await.
    • If we do not provide any database name in Mongo DB by default, it creates test database.
    • The service hits the backend API which gets data from database layer, processes it and provides response.
  • All the component names which are producers i.e. use export command within, start with capital letters. Example App.jsx
  • Smart components are responsible for rest calls And front end business logic.
  • Other General components are mainly used for rendering purpose.
    • They don’t have decision making power.
  • All the components which are consumers that is consume producer components start with lower case. Example main.jsx
  • Different hooks in React
    • Use effect
      • Use effect is used to load the content.
      • Detect changes for specific activities.
      • It is used to load content under following conditions
        • Every Render
          • UseEffect(fn)
            • Runs after every commit.
            • Sync something with the DOM/logging
        • Mount/unmount
          • useEffect(fn,[])
          • Runs on Mount -Cleanup on unmount
          • Used for subscriptions, timers, one time, initialisation.
        • On changes
          • UseEffect(fn,[a,b])
          • Runs on Mount and when a/b change
          • Fetching, recomputing derived data
    • Use selective
    • Use scratch
    • Use wrap
    • Use callback
    • UseMemo
      • Holds content directly into the memory.
      • Will only recompute Once the dependencies have changed.
      • Store data in cache memory.
  • Properties(Props)
    • We can pass data in components using tag properties.
    • We can share data from one component to another component.
    • Data is shared between components with the help of properties of tags.
    • Properties help us to send data from parent component to child component.
      • For example, we can share app name in header and footer component.
    • The child component accepts the data in the argument list.
    • Data is passed through file level nesting.
    • Properties are difficult to maintain as the data increases.
      • To send the data in well organised structure, we use redux.
    • Properties based mechanism can be used for sharing data down the line until 2 levels only and not beyond that is till first child and second child.
    • In local state, while working with props, the data only affects the specific component.
    • We utilise the components for sharing data, sharing events, styling defects, display preferences, while utilising the properties.
    • If data we are getting from store is same as sending via props, consider sending via properties only.
    • If the element is immediate child, who will be consuming the data, send the data via properties.
    • There is a lot of cost Involved in connecting to store.
  • Redux
    • Redux is used to share properties among non related components.
    • Redux it is a centralised store where we can access anything at any time.
    • Redux is preferred for a more organised code.
    • While using redux, which is a centralised storage system. We maintain whole state of application.
      • We can read, retrieve, and update data from store using redux.
      • Any change in data in store impacts all the components using that data.
    • Install using npm i @reduxjs/toolkit react-redux.
      • This library helps us to integrate redux implementation in react.
      • This is a modern approach to integrate redux.
      • react-redux is an integrated library.
      • react-redux toolkit is also called as RTK toolkit.
      • It is the official approach to run, redux under react application.
    • There is also a traditional/legacy approach to use redux in react.
      • To use the traditional approach install following libraries
        • npm i redux react-redux redux-thunk.
    • redux-thunk helps us to maintain complete executional control on our react, redux environment in backend.
    • Whenever we are going to start an operation in redux till the manipulation that happens in our store. This entire cycle is monitored by redux-thunk.
    • redux-thunk is also referred to as a middleware.
      • It internally maintains from our component executional control i.e. whenever our component performs any operation till the manipulations are over in the store during this journey thunk helps us.
    • redux is one sided flow i.e. unidirectional.
    • Working of redux environment
      • Store
        • Store is accessible to all the components.
      • Components
        • Components can read data from store.
        • The data that component get is immutable.
        • From the component we need to call the action methods to work with Redux Envirnoment.
          • We use dispatch method.
          • We use reducer/data from the state.
          • useDispatch is a hook that is used to return an object with dispatch method (thunk==) async operation.
          • Used to call our action.
      • Actions
        • Components connect with the actions.
        • Actions share data with reducer.
        • Actions will perform the rest call and do the common business logical stuff.
        • Actions pass this information to Reducer.
        • Actions pass information to Reducer via thunk.
        • dispatch() method in action starts from component/action and ends as we reach thunk. While ending it shares data with reducer.
        • dispatch() action is done by thunk.
        • dispatch() pushes data to reducer.
      • Thunk
        • Actions with the help of thunk make changes in Reducer.
        • The communication between Action and Reducer happens via thunk.
        • Thunk will start its journey from component to reducer to share the data via actions.
        • UseDispatch is used to call the action's dispatch method.
          • UseDispatch is a hook.
            • It returns an object with a dispatch method which is a thunk and follows an async operation to call our actions.
        • UseReducer is used to manage the local component store/state.
        • If we want to get any data from state we use UseSelector hook.
        • It persists the data in state using dispatch method.
        • It returns the data in immutable form.
      • Reducer
        • Reducer updates our store.
        • Reducer updates changes in our store content.
        • Reducer will make changes in centralised store.
        • Reducer takes 2 parameters a state and response from action.
  • We start with properties and local state. We only introduce redux when we actually feel the pain of property drilling or need truly global state management.
  • For enterprise application, we may require global state or centralise state.
  • Thunk
    • Thunk is a middleware.
    • Thunk carries the complete asynchronous communication enablement throughout application.
    • Thunk starts its work the moment we start consuming our action till the time reducer enters.
    • Allows all interactions in asynchronous way in redux environment.
    • Throughout this cycle, complete asynchronous communication happens.
    • When it comes to reducer to store the data, this process is synchronised.
  • Redux Life Cycle
    • Components are able to access data from store.
    • To perform changes to data components, connect with actions.
      • The actions perform REST calls and business logic operations.
    • The actions start the asynchronous journey with Thunk.
    • Once the result of business logic operations or REST calls is obtained they are sent to Thunk which sends to Reducer.
    • Till the entry point of reducer, things, go in an asynchronous way. Once the data reaches reducer the changes are stored in store in synchronous way.
  • Code Implementation Workflow
    • Declare the types.
      • Declared types are consumed by Reducer.
    • Write our reducer.
      • Reducer is consumed by action.
    • Write our action
      • Action is consumed by components.
    • Write Component.
  • Writing settings for Application
    • Declare Store
    • Root Reducer
      • Our store is connected with react application through Root Reducer.
      • RootReducer is consumed by store
        • All components reducers entries done in rootReducer.
  • We can create store using 
    • createStore() and legacy_createStore() in "redux"
      • CreateStore is supported by old redux or old react redux version.
      • To Support latest versions, we need to follow legacy_create_Store().
      • createStore is deprecated now.
      • CreateStore takes 3 parameters
        • RootReducer
        • initialState
        • applyMiddleware
          • used to integrate necessary middleware.
    • createStoreHook from react-redux
      • If we want to use store as a hook, then we have createStoreHook provided by react, redux integrated library.
  • Our store is divided into several parts.
    • Each part is a module level reducer.
    • All these are loaded by RootReducer with the help of combineReducer() function.
  • Add the store to application by wrapping it in provider element in main.jsx.
    • Provider element is parent to Router application.
    • Provider element is used to inject store details in our provider.
  • Execution Flow
    • From the component use hook UseDispatch to dispatch data to store via action and reducer.
    • To get particular element use UseSelector Hook
    • To consume action UseDispatch
    • From action share information with reducer via dispatch.
    • It will come to RootReducer and then ComponentReducer.
      • In component reducer data is destructured.
    • Reducer persists data in store.
  • Once we refresh the page our store is cleared.
  • Handling Tokens
  • Handling Validation
    • Validation notifications are given via Alerts.
    • Notifications are sent over the success part and failure part.
    • We can throw error from catch block in service.
      • These are then handled in action and dispatched accordingly to Reducer.
    • We can also throw error from catch block in action as well.
  • RTK(Redux Toolkit)
    • RTK is simple
      • Hooks are heavily used in RTK.
      • Set up for RTK is simple.
      • Lot of boiler plate code specification is reduced.
    • RTK is opinionated
    • RTK is powerful
    • RTK is effective
    • Reducer is called as slice in RTK.
    • We have a store and store has slices.
    • Slices are also called as API slices.
    • In store.js We use configureStore() Instead of createStore() to configure store.
    • In the UI, we use createSlice().
    • In Reducer Instead of switch, we use json based Implementation to toggle.
    • The thunk work or the middleware work Is done by slice directly.
    • Whenever we give a call to an event, we call dispatch method.
    • Dispatch takes us to the reducer via action.
    • Reducer takes us to the store.
    • From store via select we render the information.
    • In the slice in create slice method we define reducer as we used to define switch case in Redux.
      • We write different actions via json based implementation in slice which is equal to Reducer in Redux.
    • Redux js toolkit is implicitly capable to perform rest calls. So there is no need to install axios library.
    • In api.js we perform rest calls using create api.
      • The dispatch method from action and api calls from service are all handled by create API method.
      • In endpoint section builder, mutation is used to perform POST, PUT, DELETE.
      • builder.query is used for GET method.
      • CreateAPI works as an action and shares the results with slice.
      • The axios work is performed in the base query part of Auth API, where we create headers and base url using function fetchBaseQuery
      • In authAPI we have autogenerated hooks for all endpoints.
      • In store.js we map the reducer path to the reducer.
    • Implicitly it takes us to the same slicer based Implementation and calls the Appropriate action, First.
    • In main.jsx define store in the provider component.
      • Provider component consumes store.
    • In store we provide reducer and map reducer path to reducers.
      • This mapping is our combined state specification.
      • To access this state specification, we are getting the hook specification.
        • We get the state from the Hooks specified.
    • Reducer Path specified in API is mapped to store.js.
    • Prepare headers, we have mapped with all our actual actions.
    • Builder object helps to define and execute urls.
      • It is defined in RTK.
  • Most projects still use traditional Redux approach.
  • Creating custom hooks.
    • We define it with the help of function only which starts with use for example useToggle.
    • Toggling can be used to change state true to false and false to true.
  • References

    Comments