Answers for "use example react useReducer"

12

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>
    </>
  );
}
Posted by: Guest on June-21-2020
0

use example react useReducer

import React, { useState, useReducer } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function reducer(state, action) {
  switch (action.type) {
    case "add":
      return [...state, action.item];
    case "remove":
      return [
        ...state.slice(0, action.index),
        ...state.slice(action.index + 1)
      ];
    default:
      throw new Error();
  }
}

function FavoriteMovies() {
  const [movies, dispatch] = useReducer(reducer, [{ name: "Heat" }]);
  const [newMovie, setNewMovie] = useState("");

  const handleAddClick = () => {
    if (newMovie === "") {
      return;
    }
    dispatch({ type: "add", item: { name: newMovie } });
    setNewMovie("");
  };

  return (
    <>
      <div className="movies">
        {movies.map((movie, index) => {
          return (
            <Movie
              movie={movie}
              onRemove={() => dispatch({ type: "remove", index })}
            />
          );
        })}
      </div>
      <div className="add-movie">
        <input
          type="text"
          value={newMovie}
          onChange={event => setNewMovie(event.target.value)}
        />
        <button onClick={handleAddClick}>Add movie</button>
      </div>
    </>
  );
}

function Movie({ movie, onRemove }) {
  return (
    <div className="movie">
      <span>{movie.name}</span>
      <button onClick={onRemove}>Remove</button>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <h2>My favorite movies</h2>
      <FavoriteMovies />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Posted by: Guest on July-22-2021
-1

what does the useReducer do in react

const [state, dispatch] = useReducer(reducer, initialState);
Posted by: Guest on December-05-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language