why is a React class component converted to functional component with hooks not picking up state in event handler on doc

why is a React class component converted to functional component with hooks not picking up state in event handler on doc

Content Index :

why is a React class component converted to functional component with hooks not picking up state in event handler on doc
Tag : reactjs , By : cashshadow
Date : January 11 2021, 05:14 PM

may help you . The second parameter that you pass to useEffect tells react to skip the effect unless one of the items in the array has changed. You passed in an empty array, so other than the initial render, it will never update. Thus, you set up the event listeners with functions that have the original state in their closure, and nothing else.
To get it to update as state changes, either remove the array, or fil it with variables that your code depends on:
  useEffect(() => {
    document.addEventListener('copy', handleCopy);
    document.addEventListener('paste', handlePaste);
    return () => {
      document.removeEventListener('copy', handleCopy);
      document.removeEventListener('paste', handlePaste);
  }, [state])

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to assign a response from AXIOS to an array in state of functional component(React Hooks)

Tag : reactjs , By : s8k
Date : March 29 2020, 07:55 AM
it fixes the issue setState is async and it execute in a batch inside a scope. You are updating the state that is correct but in next line when you are doing console till that time state is not updated so it is showing the default or old value.you can use async and await. If you use class component, this.setState had one callback option which will solve this problem. But as you are using useState hook that is not available by default but there is another library for useState callback please google it. Otherwise after updating console it out side the useEffect hooks.You can get the result.

React Class vs Functional Component: When using hooks and functional components one of my functions constantly re-render

Tag : javascript , By : Tony Z
Date : March 29 2020, 07:55 AM
I wish this helpful for you So it turns out just wrapping things in useCallback doesn't work because I have other issues like button switching between disabled and active based on an answer being there.
I decided to re-write my component to have two states one that stores overall answers and the current answer in a separate state. This way I can wrap the save answer in a useCallback with only one dependency allowing for minmal re-renders but also my buttons become active/disabled.
import React, { useState, useEffect, useCallback } from "react";
import PropTypes from "prop-types";
import { Row, Col } from "react-bootstrap";

// CC
import CCProgressBar from "../CCProgressBar";
import CCButton from "../CCButton";
import CCFlowAnswer from "../CCFlowAnswer/";

// Local Assets and CSS
import "./CCFlow.css";

const CCFlow = ({ questions, answers, wipeAnswers, handleSubmit, style }) => {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [usersAnswers, setUsersAnswers] = useState();
  const [currentAnswer, setCurrentAnswer] = useState(undefined);
  const [wipe, setWipe] = useState(false);

  useEffect(() => {
    setUsersAnswers(questions.map(() => undefined));
  }, [questions]);

  // Helpers
  function onLastQuestion() {
    return currentQuestion === questions.length - 1;

  function progress() {
    const total = 100 / questions.length;
    return Math.round(total * (currentQuestion + 1));

  function loadLastAnswer() {
    setCurrentAnswer(() => usersAnswers[currentQuestion - 1]);
    setCurrentQuestion(currentQuestion - 1);

  function submitAnswers(answer, allAnswers, questionIndex) {
    const submittableAnswers = allAnswers;
    submittableAnswers[questionIndex] = answer;

  function cleanAnswers(allAnswers, wipeAnswers, wipe, questionIndex) {
    return wipe && wipeAnswers[questionIndex]
      ? allAnswers.map((answer, index) =>
          index > questionIndex ? undefined : answer
      : allAnswers;

  function loadNextAnswer(
  ) {
    const updatedUsersAnswers = cleanAnswers(
    updatedUsersAnswers[questionIndex] = answer;
      updatedUsersAnswers[questionIndex + 1]
        ? updatedUsersAnswers[questionIndex + 1]
        : undefined
    setCurrentQuestion(questionIndex + 1);

  // Actions
  function moveForward(skip) {
    const ca = skip ? "None" : currentAnswer;
    currentQuestion === questions.length + 1
      ? submitAnswers(ca, usersAnswers, currentQuestion)
      : loadNextAnswer(ca, usersAnswers, wipeAnswers, wipe, currentQuestion);

  function handleNextButtonClick() {

  function manualNextTrigger() {

  function handleSkip() {

  function handleBackButtonClick() {
    currentQuestion !== 0 ? loadLastAnswer() : window.history.back();

  const saveAnswer = useCallback(answer => {
    setWipe(() => true);
  }, []);

  return (
    <div className="ccQuestions" style={style ? style : {}}>
        <Col xs={3}>
          <h4 style={{ minHeight: "80px" }}>{questions[currentQuestion]} </h4>
          <div id="ccFlowRow">
            <CCProgressBar width="200px" now={progress()}></CCProgressBar>
          <div id="ccFlowButtons">
            <CCButton variant="dark" onClick={handleBackButtonClick}>
              {currentQuestion === 0 ? "Exit" : "Back"}
              style={{ marginLeft: "15px" }}
              variant={onLastQuestion() ? "primary" : "info"}
              disabled={currentAnswer ? false : true}
              {onLastQuestion() ? "Create" : "Next"}
        <Col xs={9}>
              currentQuestion !== 0 ? usersAnswers[currentQuestion - 1] : null

CCFlow.defaultProps = {
  questions: [],
  answers: [],
  wipeAnswers: []

CCFlow.propTypes = {
  style: PropTypes.object,
  questions: PropTypes.arrayOf(PropTypes.string),
  answers: PropTypes.arrayOf(PropTypes.elementType),
  handleSubmit: PropTypes.func,
  wipeAnswers: PropTypes.arrayOf(PropTypes.bool)

export default CCFlow;

React: Changing State in functional component also Change functional component's props value, and its Parent Class State

Tag : javascript , By : tangsty
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have a Parent Class let say Data and i am Rendering Model with checkbox list if this.state.showList is true and passing this.state.list as props to functional component (see Code) , You are mutating the state here checkboxClick:
const newState = [...state]; // shallow clone of the state array, objects inside the array are not cloned
const newElement = newState[index]; // getting reference to the original object
newElement.selected = !selected; // mutating the original object
newState[index] = newElement; // replacing the original object reference with the original object reference does nothing
const state = [{}];

const newState = [...state];
const newElement = newState[0];
newElement.selected = true;

console.log(state[0] === newElement);
const state = [{}];

const newState = [...state];
const newElement = { ...newState[0] };
newElement.selected = true;

console.log(state[0] === newElement);

Converting class based component to functional component using react hooks

Tag : javascript , By : wrb302
Date : March 29 2020, 07:55 AM
Hope this helps You have 2 options to achieve updating state values with hooks:
the first option would be to declare 2 state variables (or more, depending on the needs of the component)
const [dragSource, setDragSource] = useState(...);
const [draggedItem, setDraggedItem] = useState(...);

const onDrag = (event, item, currentDropZoneId, currentDropZoneItems) => {
  console.log("source", currentDropZoneId);


 onDrag={event => onDrag(event, item, dropZone.id)}
const [state, setState] = useState({
  dragSource: ...,
  draggedItem: ...

const onDrag = (event, item, currentDropZoneId, currentDropZoneItems) => {
  console.log("source", currentDropZoneId);
    dragSource: currentDropZoneId,
    draggedItem: item


 onDrag={event => onDrag(event, item, dropZone.id)}

React 16.7 has State Hook, can I use functional component instead of class component in any situation?

Tag : javascript , By : socurious
Date : March 29 2020, 07:55 AM
will help you Actually,there are some rules when you use hook:Don’t call Hooks inside loops, conditions, or nested functions and Don’t call Hooks from regular JavaScript functions.
You can read these rules and explanation here: https://reactjs.org/docs/hooks-rules.html
Related Posts Related QUESTIONS :
  • Unexpected user of comma operator no-sequences
  • React Native onChangeText like onChange in ReactJS
  • How to dynamically render an element on clicking a button
  • Cannot import components from react-bootstrap
  • How to prevent Office UI Fabric React DatePicker flyout from stealing focus when allowTextInput is true?
  • How delete item from redux state?
  • Uncaught TypeError: map is not a function In Reactjs with Firebase
  • Alternative to componentWillReceiveProps for my particular use case
  • Pokemon, API call Variable doesn't save
  • Rendered more hooks than during the previous render. when posting form data with React Hooks
  • How can I envoke <Link to=''> route transition from a custom function?
  • How to change certain div color base on number
  • Hide Navbar on some routes (React Router v5)
  • is it safe to ignore react's warning about calling the useState hook conditionally when only the parameter is conditiona
  • How to pass a function as a prop to React function component?
  • Creating a function that replace a letter with a line break
  • How to add and remove property from Redux state
  • Can I, (and should I), make assertions about what HTML elements a component renders using Enzyme's shallow()?
  • Testing function calls in Jest after button click (mocking fetch calls)
  • How can I show a card shadow on all sides?
  • Jest - Map through an Array of Items and test their Values
  • Run Effect hook only when both dependencies change
  • What is the difference between .ts and .tsx extensions. Both are used as extensions for typescript files in react. So wh
  • Font size of tooltip in speeddialaction of React's Material UI
  • Module Not Found - Webpack Dev Server
  • React not rendering all elements within a list of components
  • How to change attribute of a React Element
  • ReactJs: How to back focus to input field after resetting the form
  • Multilanguage in react using redux
  • React JS — how do I add child components and set calculated transformations?
  • ReactJS componentDidUpdate() prevState equals to currentState
  • TypeScript error: JSX element type 'Tree' does not have any construct or call signatures. I'm not able to import my own
  • createProvider is not exported from react-redux?
  • Error:(19, 35) TS2304: Cannot find name 'T'. Why I can't extend interface in TS?
  • How can I secure images in S3 buckets with Auth0 and a React front-end
  • React Import Multiple Functions
  • React render when props change
  • Cannot read property 'array' of undefined
  • What is the expected return of `useEffect` used for?
  • Why i need to install npm for react native app
  • How to fix 'module not found' for audio files using file-loader? Images, CSS, and JSON are working just fine
  • Can't render the component received as a prop.children in my parent component
  • rootInstance.findByType("input"); Giving Expected 1 but found 2 instances with node type : "undefined&quo
  • Reset state to initial state only for specific state variables
  • Get error TS2322: Type 'any' is not assignable to type 'never'
  • Is it possible to update the store outside of the Provider context in Redux?
  • Copy to clipboard is copying value with two newlines
  • How to test useRef with the "current" prop in jest/enzyme
  • How to remove value of each key in Async Storage in React Native at the time of Logout
  • Is there a simpler way to write this React code
  • Auth0. How to get user's permissions in access token?
  • this.setState is not updating the state property
  • for loops in reacts js
  • The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:3000, http://localhost:3000', but on
  • Slowly implementing redux to an existing React.js project
  • how to use document.querySelector().innerHTML in react
  • Pass params to firestore collections
  • BrowserRouter vs Router with history.push()
  • React Formik onSubmit RestAPI called twice, once click a submit button
  • Can this assignment be made simpler by destructuring?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com