Categories
React

How to Reload State from Props in a Component Created with React Hooks?

Spread the love

Sometimes, we’ve to reload a state according to a prop value that’s passed in.

In this article, we’ll look at how to reload states from props in a component created with React hooks.

Watch Props Change with useEffect

The useEffect hook lets us watch for changes of reactive values, which includes props.

Therefore, we can use the useEffect hook to watch for changes of prop values and update our state accordingly.

For instance, we can write:

import { useEffect, useState } from "react";

const Counter = ({ count }) => {
  const [countState, setCountState] = useState(count);

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

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

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

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

We have the Counter component that takes the count prop.

Inside the component, we have the countState state that’s set to count ‘s value as its initial value.

Below that, we call the useEffect hook with a callback that calls setCountState with count to set countState ‘s value to be the same as count ‘s value.

In the 2nd argument of useEffect , we pass in an array with the count prop to watch for changes in the count prop and trigger the useEffect callback to be called.

Then in the App component, we have the count state initially set to 0.

And we have a button that calls a function that calls setCount to update the count state by incrementing it by 1 with the callback we pass in.

The callback gets the current value of count as the parameter and returns the new value which has been increased by 1.

Below the button we show the Counter component where we pass in the count prop by setting it to the count state as its value.

Now when we click the increment button, we see the latest countState rendered via the count prop.

Conclusion

We can update a state according to changes of a prop by watching it with the useEffect hook and then calling the state change function to update the state according to the prop value in the useEffect callback.

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 *