In Simple react class component we used to change the props to state this way:
constructor(props) { super(props) this.state = { pitch: props.booking.pitch, email: props.booking.email, firstName: props.booking.firstName, arrivalDate: props.booking.arrivalDate } }
But I am not aware of how to do it in new feature as Hooks, but I am trying to do it this way.
const GenerateDescHook = ({ description: initialDesc }) => { const [description, setDescription] = useState(null) useEffect(() => { setDescription(initialDesc) }, {}) function handleChangeVariance(newVariance) { setDescription({ ...description, template: { ...description.template, variance_name: newVariance, }, }) } }
Basically, I just need to change description props, which coming from another parent component to turn to state. Pls, could you show me how to do it in new way as Hooks way?
Passing props to state using useState Hooks import React, { useState } from 'react'; const Profile = props => { const [profileState, setProfileState] = useState(props); return ( <div> <p> <strong>Name:</strong> {profileState.name} </p> <p> <strong>Email:</strong> {profileState.
Component { state = { description: '' } constructor (props) => { const { description } = props; this. state = {description}; } render () { const {state: { description }} = this; return ( <input type="text" value={description} /> ); } } export default SecondComponent; Update: I changed setState() to this.
To update state when props change in React:Pass the props as dependencies to the useEffect hook. Every time the props change, the logic in useEffect is reran.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Read the Motivation to learn why we're introducing Hooks to React.
The problem in your code is with {}
. UseEffect hook expects and array, not an object. Use [initialDesc]
instead.
This is how you reset component state when props change
const GenerateDescHook = ({ description: initialDesc }) => { const [description, setDescription] = useState(null) useEffect(() => { setDescription(initialDesc) }, [initialDesc]); }
This is how you initialize component state to prop value on first render only
const GenerateDescHook = ({ description: initialDesc }) => { const [description, setDescription] = useState(initialDesc); }
You can pass your initial state as first argument to useState
like this:
const GenerateDescHook = ({ description: initialDesc }) => { const [description, setDescription] = useState(initialDesc) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With