1

How do I get the newly updated data from react hooks or useEffect?

I loaded the parent components with the title: Shoes then change the input to "New Shoes" but the data inside my child components doesn't change, its still "Shoes". how do I get it updated?

in the parent components:

<UrlInput
   value={url}
   title={title}
   baseURL={baseURL}
   onChange={this.onURLChange}
/>

Child component

const UrlInput = ({title}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(newTitle)
     })

  return (

  );
};
1
  • 1
    Why Is the title variable with a capital T in your useState constructor? Commented Jun 9, 2020 at 5:27

3 Answers 3

3

You should add title as a dependency to useEffect and update state with title and not newTitle. Also the original state needs to be set with title and not Title.

const UrlInput = ({title}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(title)
     }, [title]);

  return (

  );
};

P.S. Also its an antipattern to copy props into state when state is directly derivable from props unless you need to modify the state locally.

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

1 Comment

Could you please share how you are updaring title in parent and does it trigger a re-render in child
1
const UrlInput = ({title, ...rest}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(title)
     },[title]) 

  return (

  );
};

try replacing the code with the above one .You should pass a new value into setTitle() you were passing the same variable that stored the previous value.

Comments

0

For the get, any state-specific change in a component use the useEffect(() => {},[specific condition here]).

You can follow this code here.

in the parent components:

const [title, setTitle] = useState('');  // initial state parent 
const onURLChange = e => setTitle(e.target.value) ; set state parent from children triger 

<UrlInput
    value={url}
    title={title}
    baseURL={baseURL}
    onChange={this.onURLChange}
/>

Child component

const UrlInput =props => {
    const [newTitle, setTitle] = useState(props.Title);

     useEffect(() => {
         console.log(title)
         setTitle(newTitle)
     },[props.Title])

  return (

  );
};

Comments

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.