0

I'm new to React Hooks and I'm facing this problem :

  • App component initializes a map from localStorage with useEffect
  • it passes this map to child component Hello

Then :

  • child component copy this map in its own state and use it manage values editions.

Problem is, as you can see in this stackblitz console log :

parent map: undefined --- child map: undefined // map is first pass empty to the child component
parent map: world --- child map: undefined     // then it's populated by parent component effect but child state is not updated

How can I manage proper initialization of map values in child component? Do not hesitate to challenge the whole thing, I'm not sure to use effects properly here.

2 Answers 2

3

you need to have a useEffect in your child component to copy over the changing prop that parent sends down since you are initializing your local state from that prop.

import React, {useEffect, useState } from 'react';

export default ({ initialMap }) => { 

  const [map, setMap] = useState(new Map(initialMap));
  console.log(`parent map: ${initialMap.get('name')} --- child map: ${map.get('name')}`);

  // this is what you need
  useEffect(() => {
    setMap(new Map(initialMap))
  }, [initialMap])

  const onChange = (value) => {
    setMap(prevMap => {
      prevMap.set('name', value);
      return prevMap;
    });
  };

  return (
    <div>
      <label>Input initial value should be 'world':</label>  
      <input value={map.get('name')} 
        onChange={e => onChange(e.target.value)} />
    </div>
  ); 
};

Sign up to request clarification or add additional context in comments.

Comments

2

Copying state like that is an antipattern because it creates two, unnecessary, sources of truth. It's better to pass value, along with onChange handler to children. This way you have one source of truth, but you can access, and control value from children component.

I have example here: https://stackblitz.com/edit/react-hpxvcf

Also, you have to create new Map() when changing state, so React know to rerender components.

1 Comment

I agree with this for most of the case but here I need to copy original values to let user save globally his modifications or cancel them. It doesn't appear in the stackblitz I provided though. Thanks for your advice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.