Home > Software design >  React Hooks - What is the recommended way to initialize state variables with useState() from props
React Hooks - What is the recommended way to initialize state variables with useState() from props

Time:06-10

I'm asking me, if there is (and if yes, what is) the recommended way to initialize state variables in React hooks with a value from the props. So I assume I have a component like this:

function SomeComponent(props) {
    return (
        ....
    );
}

I can use useState to create a variable for this component, like this:

const [someVariable, setSomeVariable] = useState('someValue');

So far so good. My question is now, if I want to initialize the variable with a value from props, is it recommended to to it directly like this:

function SomeComponent(props) {
    const [someVariable, setSomeVariable] = useState(props.someValue);
}

or is it better to initialize it with null and then use useEffect() to set the value on load:

function SomeComponent(props) {
    const [someVariable, setSomeVariable] = useState(null);

    useEffect(() => {
        setSomeVariable(props.someValue);
    },[])
}

Maybe there are more ways, too. I was just wondering if there is a recommendation here or if in the end it doesn't matter which way you use. Many thanks for any comments in advance.

CodePudding user response:

You should go with the first approach. This is the standard, idiomatic React way.

function SomeComponent(props) {
    const [someVariable, setSomeVariable] = useState(props.someValue);
}

The useEffect approach would also work but you don't have any reason to do it, not to mention the state would be null the first time your component renders.

CodePudding user response:

It is better to use useState(props.someValue) instead of setting it in useEffect because useEffect is executed after react completes rendering the component and doing so will trigger a re-render because you are setting a new state. If you set it in useState you will be able to avoid that extra re-render.

Edit: Depending on the logic of your component you may have to handle the null state in your component in case you do it in useEffect

CodePudding user response:

If the props do not changes, you do not need to use useState.

If it changes, do this:

function SomeComponent(props) {
    const [someVariable, setSomeVariable] = useState(props.someValue);

    useEffect(() => {
        setSomeVariable(props.someValue);
    },[props.someValue])
}

Read this question & answer to understand why you need to do this.

React.useState does not reload state from props


I would do it this way:

function SomeComponent({someValue}) {
    const [someVariable, setSomeVariable] = useState(someValue);

    useEffect(() => {
        setSomeVariable(someValue);
    },[someValue])
}
  • Related