Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

usereducer react

import React, { useReducer } from 'react'
import { render } from 'react-dom'

const types = {
  PET: 'PET',
  COLOR: 'COLOR',
}

const reducer = (state, action) => {
  switch (action.type) {
    case types.PET:
      return { ...state, pet: action.value }
    case types.COLOR:
      return { ...state, color: action.value }
  }
}

const initialState = {
  color: 'black',
  pet: 'cat',
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <div>
      <label>Choose a color and a pet: </label>
      <br />
      <select
        value={state.color}
        onChange={event => {
          dispatch({ type: types.COLOR, value: event.target.value })
        }}
      >
        <option value="black">Black</option>
        <option value="pink">Pink</option>
        <option value="blue">Blue</option>
      </select>
      <select
        value={state.pet}
        onChange={event => {
          dispatch({ type: types.PET, value: event.target.value })
        }}
      >
        <option value="cat">Cat</option>
        <option value="dog">Dog</option>
        <option value="mouse">Mouse</option>
      </select>
      <br />
      <br />
      You chose a {state.color} {state.pet}
    </div>
  )
}

render(<App />, document.querySelector('#app'))
Comment

useReducer

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
Comment

useReducer

import './App.css';
import { useState, useReducer } from 'react';


function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return ({ ...state, count: state.count + 1 })
    case 'decrement':
      return ({ ...state, count: state.count - 1 })
    case 'tgColor':
      return ({ ...state, color: (!state.color) })
    case 'handleInputChange':
      return ({ ...state, name: action.payload })
  }
}

function App() {

  const [state, dispatch] = useReducer(reducer, { count: 0, color: false, name: "" })

  // const [name, setName] = useState("")
  // const [count, setCount] = useState(0)
  // const [color, setColor] = useState(false);

  const handleInputChange = (e) => {
    dispatch({ type: "handleInputChange", payload: e.target.value })
  }

  const colorCode = "#b81f00";

  return (
    <div className="App">
      <form action="">
        <input type="text" onChange={handleInputChange} value={state.name} placeholder="Enter Name" />
      </form>
      <h3 style={state.color ? { color: "red" } : { color: "black" }}>{state.count}</h3>
      <button className="btn" onClick={() => dispatch({ type: "increment" })}>+</button>
      <button className="btn" onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button className="btn" onClick={() => dispatch({ type: "tgColor" })}>Color</button>
      <h2 style={state.color ? { color: "red" } : { color: "black" }}>{state.name}</h2>
    </div>
  );
}

export default App;
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

usereducer

import React from "react";
import { useReducer } from "react";
const initialState = {
  count: 0,
};
type ReducerProps = {
  state: any;
};
const reducer = (state: state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + action.payload };
    case "decrement":
      return { count: state.count - action.payload };
    default:
      return state;
  }
};

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      Count : {state.count}
      <button
        onClick={() => {
          dispatch({ type: "increment", payload: 1 });
        }}
      >
        Increment ++
      </button>
      <button
        onClick={() => {
          dispatch({ type: "decrement", payload: 1 });
        }}
      >
        Decrement --
      </button>
    </div>
  );
};

export default Counter;
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

useReducer Hooks

const [state, dispatch] = useReducer(reducer, initialArg, init);

const initialState = {count: 0};

function reducer(state, action) {
  
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
const [state, dispatch] = useReducer(
    reducer,
    {count: initialCount}
  );
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

React useReducer Hook

import { useReducer } from "react";
import ReactDOM from "react-dom/client";

const initialTodos = [
  {
    id: 1,
    title: "Todo 1",
    complete: false,
  },
  {
    id: 2,
    title: "Todo 2",
    complete: false,
  },
];

const reducer = (state, action) => {
  switch (action.type) {
    case "COMPLETE":
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};

function Todos() {
  const [todos, dispatch] = useReducer(reducer, initialTodos);

  const handleComplete = (todo) => {
    dispatch({ type: "COMPLETE", id: todo.id });
  };

  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input
              type="checkbox"
              checked={todo.complete}
              onChange={() => handleComplete(todo)}
            />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Todos />);
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

useReducer React

import React, { useReducer } from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      throw new Error();
  }
};

const UseReduceExample = () => {
  const [state, dispatch] = useReducer(reducer, initialCount );

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default UseReduceExample;
Comment

useReducer

function init(initialCount) {  return {count: initialCount};}
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    case 'reset':      return init(action.payload);    default:
      throw new Error();
  }
}

function Counter({initialCount}) {
  const [state, dispatch] = useReducer(reducer, initialCount, init);  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({type: 'reset', payload: initialCount})}>        Reset
      </button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
Comment

useReducer() hook react

code snippet 

https://codesandbox.io/s/usereducer-demo-zxguu?file=/src/App.js
Comment

usereducer

  const [state, dispatch] = useReducer(
    reducer,
    {count: initialCount}  );
Comment

usereducer react

const [state, dispatch] = useReducer(reducer, initialArg, init);
Comment

usestate or usereducer

//When it's just an independent element of state you're managing

useState
Comment

useReducer

function reducer(state, action) {
  switch (action.type) {
    case 'incremented_age': {
      // ✅ Instead, return a new object
      return {
        ...state,
        age: state.age + 1
      };
    }
Comment

PREVIOUS NEXT
Code Example
Javascript :: react usereducer 
Javascript :: javascript time 
Javascript :: add toaster in angular 
Javascript :: leaflet circle get bounds 
Javascript :: javascript progress of xml http request 
Javascript :: Material-ui add comment icon 
Javascript :: node.js ping 
Javascript :: react native navigation change header title 
Javascript :: how to minimize electron app to tray icon 
Javascript :: use setstate in function component 
Javascript :: uncaught (in promise): both the table and dtoptions cannot be empty 
Javascript :: count javascript 
Javascript :: for each loop with arrowfunction 
Javascript :: app script map fit markers 
Javascript :: jquery wait for function to finish 
Javascript :: webpack-bundle-analyzer react 
Javascript :: js stop typing event 
Javascript :: spotify web player 
Javascript :: remove duplicates multidimensional array javascript 
Javascript :: Map and Filter methods used together 
Javascript :: foreach in javascript skip first 
Javascript :: drupal 9 get nid from node 
Javascript :: Handle click outside a component in react with hooks 
Javascript :: change property in array of objects javascript 
Javascript :: how to loop trough an object java script 
Javascript :: javascript default parameters 
Javascript :: debouncing js 
Javascript :: js refresh 
Javascript :: javascript Convert to Boolean Explicitly 
Javascript :: stop() in jquery 
ADD CONTENT
Topic
Content
Source link
Name
4+5 =