Skip to main content

React useReducer hook and how to use it in a small and big application

some little intro about  mutation in javascript 

//befor starting object are mutable means you can change it
//deep copy a object first way
//1
const objectA = { a: 100, b: 100 };
const objectB = { ...objectA };
objectB.= 200;

console.log(objectB);
//2nd
const objectC = {
  a: objectA.a,
  b: objectA.b
};
objectC.= 1000;
console.log(objectC);
console.log(objectA);

//another way to create deep copy nested object
let nobject = {
  a: 10,
  b: 20,
  c: {
    name: "manish",
    age: 21
  },
  arr: [1, 2, 3, 4, 5]
};
//deep copy of nobject
let nobject2 = {
  a: 50,
  b: 100,
  c: { ...nobject.c, age: nobject.c.age + 10 },
  arr: [...nobject.arr]
};
console.log(nobject2.c);

//useReducer simple example
import React, { useReducer, useState } from "react";
import "./style.css";
//add your action like const so you can change them from only one place
const Action = {
  INCREMENT: "increment",
  DECREMENT: "decrement"
};

//reducer is a function with two parameter one is current state and other is action. reducer would return a new state based on action or new object. don't mutate current state object just make a deep copy and change it

//don't do
/*
  let obj={
    name:"xyz",
    age:22
  }
  obj.name="abc" 
  you are mutating current object 
*/
//do like this
/*
  let obj1={}; a is different
  let obj2=obj1; same memory reference don't do
  let obj2=[...obj]; deep copy do it
*/


 Learn more about useReducer (hook) below link 

https://reactjs.org/docs/hooks-reference.html#usereducer

why we need useReducer hook

1. state management in react is not that easy as it looks for example if you have a parent component and it contains some child component now you can deal with state changes using props or you can say passing props from parent to child but suppose there is a situation where two component don't have any relationship between them passing props and managing state is not that easy or nearly impossible because that two-component don't have any relationship between each other so one way to get rid of this using Redux which is a predictable state management libarey but now suppose your app is not that big than...

useReducer is a solution here is a small example where using useReducer I am trying to solve a simple count increment problem.

example

step1:- import useReducer from react

import React, { useReducer, useState } from "react";


Step2:-define action 

//add your action like const so you can change them from only one place
const Action = {
  INCREMENT: "increment",
  DECREMENT: "decrement"
};


step3:define reducer which is a pure function and always return a new state 


const simpleReducer = (state, action) => {
  switch (action.type) {
    case Action.INCREMENT:
      return {
        count: state.count + 1,
        action: "plus"
      };
      break;
    case Action.DECREMENT:
      return {
        count: state.count - 1,
        action: "minus"
      };
      break;
    default:
      return state;
  }
};


the full example is below 


https://stackblitz.com/edit/manish-usereducer-simple 


useReducer can be used to solve complex state management problem below is a mid-level todo list using useReducer.


https://stackblitz.com/edit/manish-usereducer-complex


in most cases, you can don't need Redux anymore even for big apps you can easily handle all those state management stuff using usecontext and useReducer.


 



Comments

Popular posts from this blog

Better Memory management with PixiJS or How to manage cpu and cpu memory in PixiJS.

PixiJS is my favorite framework when i am looking for a web games specially for mobile or desktop  PixiJS is fast blazing fast and you can get a decent FPS even on older device.   so here is my optimization techniques for PixiJs 1. manage your sprites in a better way use spritesheet to reduce the draw calls create big sprite sheet which contain multiple sprites can be draw in gpu with a single draw call. use TexturePacker  https://www.codeandweb.com/texturepacker  best tool when its comes to spritesheet 2. for floating point calculation round off calculation for example let  speed = 0.75 ; let  position = 100 ; console . log ( Math . round ( speed * position )) 3. don't create very big canvas when u need a big canvas size game just try to create a small canvas and translate it. 4. its very important one managing TextureCache in memory you can get all TextureCache list by using  Object.entries(PIXI.utils.TextureCache); so even you use ap...

adding particles Effect in pixijs using https://pixijs.io/pixi-particles-editor/

adding particle in pixijs is very easy using the below tool more information can be found below https://github.com/pixijs/pixi-particles https://pixijs.io/pixi-particles-editor/ required packages  /// < reference path = "node_modules/pixi-particles/ambient.d.ts" /> import 'pixi-particles' code of particle delcare a     global variable   private emitter ?: Emitter ; const img = PIXI . Texture . from ( "./assets/images/particle.png" ); this . emitter = new Emitter ( this ,[ img ],{ "alpha" : { "start" : 0.62 , "end" : 0.39 }, "scale" : { "start" : 0.1 , "end" : 0.9 , "minimumScaleMultiplier" : 1.25 }, "color" : { "start" : "#ffff8f" , "end" : ...

DEEP COPY OF A OBJECT IN JAVASCRIPT IN A GOOD WAY

 so suppose i have a object which contain 2 values one x and other y let point={x:100,y:200}; now i wld try to copy this object to a another object let other=point;  if i change other array value it would changes the point array to like this other.x=500; console.log(point.x); console.log(other.x); that not what we want the reason behind this both variable referencing towards same memory address.  in c++ we have three options       1. we can pass variable by value that would create a new copy      2. by reference same as above        ...