简体   繁体   中英

Use useEffect to reinitialize useState

I have a component with a <div contentEditable /> inside. The component is initialized with a initialValue . The onChange handler updates the value . It looks something like this:

const Editable = ({ initialValue }) => {
  const [value, setValue] = useState(initialValue);

  return (
    <div contentEditable onChange={event => setValue(event.currentTarget.value)}>
      {value}
    </div>
  );
};

Now if the parent components passes a new initialValue , value and therefore the content of the div doesn't update since the state is already initialized.

Is it fine to use useEffect as follows in such a case or is there any other way?

const Editable = ({ initialValue }) => {
  const [value, setValue] = useState(initialValue);

  useEffect(() => setValue(initialValue), [initialValue]);

  return (
    <div contentEditable onChange={event => setValue(event.currentTarget.value)}>
      {value}
    </div>
  );
};

It's completely fine to use it that way. You may want to rename initialValue to something like value to make it clear that it's not just the default value.

What you could do to clear up your code is create a custom hook that handles that exact situation like so:

const useUpdatingState = (value) => {
  const [internalValue, setInternalValue] = useState(value);
  useEffect(() => {
    setInternalValue(value)
  }, [value]);
  return [internalValue, setInternalValue];
};

This would make your code a little more readable and make the code reusable in other parts of your code where you would want such behaviour.

As proposed in the question, a useEffect is the correct solution.

const Editable = ({ initialValue }) => {
  const [value, setValue] = useState(initialValue);

  useEffect(() => setValue(initialValue), [initialValue]);

  return (
    <div contentEditable onChange={event => setValue(event.currentTarget.value)}>
      {value}
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM