Categories
React

How to Fix the React useState Hook Not Setting Initial Value Problem?

Spread the love

The useState hook lets us create state variables in our React components.

It takes an argument for the initial value of the state.

Sometimes, we may want to set the initial value of a state from props.

And we want to update the initial value when the prop value changes.

In this article, we’ll look at how to fix the React useState hook with the latest prop value.

Updating a State When a Prop Updates

To update a state when a prop updates, we’ve to watch the prop value with the useEffect hook.

Then in the useEffect callback, we can call the state setter function to update the state value with the prop’s value.

For instance, we can write:

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

const Count = ({ count }) => {
  const [num, setNum] = useState(count);

  useEffect(() => {
    setNum(count);
  }, [count]);

  return <p>{num}</p>;
};

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <div className="App">
      <button onClick={() => setCount((c) => c + 1)}>increment</button>
      <Count count={count} />
    </div>
  );
}

In the Count component, we have the useState hook with the count value as the argument.

This sets num to count initially.

Then we have the useEffect hook that watches the count value by passing it into the array in the 2nd argument.

Then in the callback, we call setNum to update the num value and render that in the return statement below that.

In App , we have the count state created with the useState hook.

Then we call setCount in the onClick handler of the button which updates the value of the count state.

And we pass the count value as the value of the count prop in the Count component.

Now when we click on the increment button, we see the num value update and the latest value of it displayed.

Conclusion

We can make sure that a React component state updates when the prop value changes by watching the prop’s value with the useEffect hook and then call the state setter function in the useEffect callback with the prop’s value as its argument.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *