M
M
miliko mikoyan2019-07-17 19:44:04
React
miliko mikoyan, 2019-07-17 19:44:04

If the props change, how can I give an initial value to avoid the anti-pattern effect?

I am using react hooks. If the props are changed, what are the ways to get the initial value? I want to avoid the anti-pattern effect.
situation 1
before building the DOM.
as far as I understand, using useMemo.if there are other options that you can show them will be suitable for these purposes.
situation 2
after DOM
And in this option useLayoutEffect, useEffect.if there are other options you can show them.

import React, { useState, useMemo, useLayoutEffect, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
const X = () => {
  const [x, setX] = useState(0);
  return (
    <div>
      <div>
        <Y x={x} />
      </div>
      <div onClick={() => setX(x + 1)}>{"go"}</div>
    </div>
  );
};

function Y({ x }) {
  const [y, setY] = useState(x);

 /* useMemo(() => {
    console.log("");
    setY(x);*/
  }, [x]);
  /*useEffect(() => {
    console.log("");
    setY(x);
  }, [x]);*/
  /*useLayoutEffect(() => {
    console.log("");
    setY(x);
  }, [x]);*/
  console.log(y);
  return <div className="App">{console.log(y, "DOM")}</div>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<X />, rootElement)

I don't think it's good practice to use all those hooks. but I don't see any other solution. Maybe there is a third option without using hooks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-17
@miliko0022

I think it's more correct to use useEffect here:

function Y({ x }) {
  const [y, setY] = useState(x);
  useEffect(() => {
    if (x !== y) {
      setY(x);
    }
  }, [x, y]);

  return ( ... );
}

useMemo is best used for props-based calculations, returning callbacks using some kind of debounce, but not for state changes during rendering.
Well, and most importantly, the library can forget the memorized value at any time and recalculate it again, about which there is a note in the documentation . So you can lose the current state.
The third option is to use class components and lifecycle methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question