Converting from a stateful component to a functional component with hooks in React

Daniel Andrew
2 min readOct 27, 2021

--

Howdy folks, hope alls well with y’all. Thought I would go into something I have found very useful, which is converting from stateful component to using hooks in React.

This will also go into the glorious useState and useEffect hooks (more on that next blog). A wonderful reason for moving across to hooks is they make everything a lot more clear when you are changing the state, and much easier to pull things out and keep an eye on them along the way.

Let’s start with a simple one shall we?

A nice basic component. First, lets get the important bits from React,

We want both useEffect and useState otherwise this isn’t gonna play ball.

Now we want to convert the component to a const function, and pass props in. State can also be removed, as now we just want to keep a few useState constants for whatever we are doing, in this case we just want an editing boolean and a character object.

These are set via the new useState hook we have imported.

They are used in the format of :

const [thing, setThing] = useState()

You can then set the initial value of whatever you want the state to be in the useState parameters.

From then on if you want to change the state of the ‘thing’ you just call the setThing() function, passing the new value in the parameters.

Make sure you go through each reference to this or this.state and remove them, we wont be wanting them anymore!

Lastly as its now a functional component we don’t worry about render() anymore and just need to return what we want!

You can view the converted component below in its new functional glory!

Isn’t that better, managed to get rid of an entire function (handleEdit), character is now set differently as well (which will become more useful in my next blog) and it looks a lot nicer!

Next time i’m going to go into the CreateCharacter component and see if i can do the same. Its a bit more complex than this nice easy component, but lets give it a go!

Hope you have enjoyed this and found it useful.

Peace.

Dan

--

--

Daniel Andrew
Daniel Andrew

Written by Daniel Andrew

Old enough to have enjoyed Sid Miers Pirates on Windows 3.1 and deciding to delve out into more interesting waters.

No responses yet