Categories
React Answers

How to Initialize State from Props in a React Component?

Spread the love

Sometimes, we want to initialize state from props in a React component.

In this article, we’ll look at how to initialize state from props in a React component.

Initialize State from Props in a React Component

To initialize state from props in a React component, we can watch the prop’s value with the useEffect hook, then we can call the state setter function to set the state’s value to the prop’s value.

For instance, we write:

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

const Child = ({ text }) => {
  const [val, setVal] = useState();
  useEffect(() => {
    setVal(text);
  }, [text]);

  return <div>{val}</div>;
};

export default function App() {
  return <Child text="hello world" />;
}

to create the Child component with the text prop.

We create the val state with the useState hook.

Then we call the useEffect hook with a callback that calls setVal with text.

The 2nd argument is set to an array with text so that we watch for changes in the text prop.

And then we render val in the div.

In App, we add the Child component and set the text prop.

Therefore, we should see ‘hello world’ rendered.

Conclusion

To initialize state from props in a React component, we can watch the prop’s value with the useEffect hook, then we can call the state setter function to set the state’s value to the prop’s value.

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 *