Tags down


Render functional component on variable change

By : Sraban Rahman
Date : October 17 2020, 06:10 AM
will be helpful for those in need a function component in react is equivalent to the render() function in a class component.
so in your case you're adding an eventListener every time the component is re-rendered which creates a memory leak, you should use useEffect hook instead to add it once and remove it when the component/hook is destroyed.
code :
export const myComponent = (props: compPropsType) => {
    const myClassNames ....
     const [objectList, setObjectList] = useState([])

  const onHashChanged = () => {

    let newObjectList = getObjectList(window.location.hash, props.pageTree)

  useEffect(() => {
    window.addEventListener('hashchange', onHashChanged)
    return () => window.removeEventListener('hashchange', onHashChanged)
  }, [])
    return (
        <header className={headerClassNames}>
            <Block className={...}>
            <myChildComp objList={objectList}>

Share : facebook icon twitter icon

Adding a variable to the store upon a functional component's initial render

By : user3034744
Date : March 29 2020, 07:55 AM
I hope this helps . This is the sort of thing that useEffect is intended for. If you specify an empty array for the second argument (the dependency array) then it will only run on the first render, and you can use the return function to remove it.
Here's roughly how to do it:
code :
const Counter = (props: {startingValue: number}) => {
    const dispatch = useDispatch();
    const variable = useSelector(store => store.storedVariable);
    useEffect(() => {
        dispatch({type: 'store-starting-value', payload: startingValue})
        return ()=>{
             dispatch({type: 'clear-starting-value'})
    }, []);


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

By : user3236653
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.
code :
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

By : Jose
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:
code :
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);

props.history.push inside functional component renders doesn't render the component

By : gkshida
Date : March 29 2020, 07:55 AM
wish helps you Posting this incase anyone else has this peculiar issue. I solved this issue using the following logic: I check in the component that's calling the login function, if the isAuthenticated is true I redirect to the homepage.

Does a Stateless Functional Component equal to a Component which just has a render method?

By : Palli Srinivas
Date : March 29 2020, 07:55 AM
With these it helps Like the question above: , Basically, here's the short breakdown:
Related Posts Related Posts :
  • How can I use function chaining with dates in JavaScript?
  • What is the difference between "delete" and "Reflect.deleteProperty()"
  • How to get attributes of individual elements in jquery array
  • Why do I get different results with "=" vs. "===" in javascript with Conditional (Ternary) Operators
  • I am trying to hold value of document.getElementById("image").src=UserInput +".gif"
  • Array being pushed into another array isn't displaying
  • Is there a React.js NPM module or any other solution for image/object mutli-selection?
  • 80% Javascript Solution for Flags in Codility
  • I want to display background while scrolling down
  • RegEx for matching text between two tags
  • Does having a lot of inner 'helper' functions inside a functional stateless react component will result in worse perform
  • How to submit a form through a button outside the form?
  • ESLint: Use callback in setState when referencing the previous state
  • How to parse state from one component to another in my example?
  • Visible Html select option showing under hidden items
  • Create SVG circle using path with 6 segments
  • Getting error while reading from a text file
  • Read a value from JSON Array without entity
  • Checkbox check or uncheck value null
  • Displaying multiple slider values to users
  • Am doing the destructing right?
  • VueJS data-bind object styling not working
  • Combine array and object destructuring
  • Execution skips promise statements
  • sort an array of objects leaving first field
  • how to highlight table cells in a certain way when hover over
  • Problems when using Chosen Selectors in external helper functions
  • Need to merge two objects together that each have an array to the matching IDs
  • How to get previous 6 months date from current date in javascript
  • how to get object value only without mentioning key from array list using ngFor in angular 7
  • Plugging into on_page_change events in testcafe
  • WithStore: Cannot read property 'state' of undefined (pure-react-carousel)
  • fullcalendar event info in modal popup
  • How do i reduce time complexity of this code
  • Deep comparing object props in React not working as expected
  • JavaScript method to remove case insensitive duplicates from string/Numbers
  • When to use parentheses after function name call (es6)
  • Convert list of Objects when the levels are given in an array
  • template variable always undefined ngOnChanges
  • RegEx for matching the first word
  • Render different au-target-id in aurelia repeat
  • Why does the function start before the button is pressed?
  • where can I vote for changes to javascript?
  • Change the digit format pagination in the slider
  • Hover/focus state activated initially on page load
  • Why do my normal sync codelines, works like async?
  • How to prevent or disable Bootstrap 4 popover auto positioning behavior (Self adjusting behavior)
  • What is the meaning of ({})?
  • How do I make a link to a property if the property is yet to be declared? (In a Class)
  • Getting Promise as return value inside FlatList React-native
  • Why can't you access JSON directly from the response in Fetch API?
  • How to grab value out of this nested array
  • function is not returning any value
  • "Cannot read property 'map' of undefined (React.js)"
  • How do I extract the contents of a specific json within the html?
  • How do I assign a src attribute to the background-image of another element?
  • How to access a public method from a wrapped Component using TypeScript?
  • Errors while looping through the objects
  • How to fix "TypeError: fsevents is not a constructor" react error
  • Invalid JSON characters after processing JSON file in Vue.js
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk